温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++11 初始值{}与()的区别

发布时间:2020-03-01 16:35:01 来源:网络 阅读:327 作者:yaxinsn 栏目:系统运维

#include <stdio.h>
#include <stdlib.h>
using namespace std;
/*
 *  A1 类对象成员变量的默认值;
 *//B1 初始值列std::initializer_list
 * B2 使用初始值列initializer_list
 *
 *
 * */
class Hello{

        char* hello = 0;//A1 类对象成员变量的默认值;
public:
        ~Hello();
        Hello(const char* h);
        Hello(const char* h,const char* j);
        Hello(std::initializer_list<char*>);//B1 初始值列
        Hello(const Hello &obj);
};
Hello::Hello(const Hello &obj)
{
        cout <<"call copy constructor "<<endl;
        hello = strdup(obj.hello);
}
#if 1
Hello::Hello(const char* h)
{
        hello=strdup(h);
        cout <<__func__<<endl;

}
Hello::Hello(const char* h,const char* j)
{
        hello=strdup(h);
        cout <<__func__<<":" <<__LINE__<<" Hello(char* h,char* j)"<<endl;

}
Hello::Hello(std::initializer_list<char*> vals)
{
        char* x=(char*)vals.begin();
        hello=strdup(x);
        cout <<__func__<<":" <<__LINE__<<" Hello(std::initializer_list<const char*>)"<<endl;
}
#endif

#if 1
Hello::~Hello()
{
        if(this->hello)
                free(this->hello);
}

#endif

int main()
{
        int a{0};
        int b(0);
//      int c{0.3}; error 不可窄化
        int d(0.3);

        Hello H1("H1","H1");
        Hello H2{"H2","H2"}; //B2 使用初始值列initializer_list
        Hello H3{"H2","H2","XX"}; //使用初始值列initializer_list
        return 0;
}

总结:
int b(1.4)可以窄化与类型转换。{}不可以。
初始化用户自定义的类对象时,{}会优先使用initializer_list的构造函数。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI