c++类大括号初始化

以下是大括号初始化的几种用法

如果程序员自己没有写明类的构造函数,那么在请使用声明的成员的顺序提供列表元素。如:

class text{
    int a;
    double b;
    bool c;
};
int main(){
    text the_class{1, 2.0, false};
}

如果已经写好了一个构造函数,请按照构造函数的参数列表提供元素。如:

class text{
    int a;
    double b;
    bool c;
public:
    text(bool the_c, double the_b, int the_a) : a{the_a}, b{the_b}, c{the_c}{
    }
};
int main(){
    text the_text{false, 2.0, 1};
}

如果默认构造函数存在,我们可以使用空大括号来调用。如:

class text{
        int a;
    double b;
    bool c;
public:
    text (){}
    text(bool the_c, double the_b, int the_a) : a{the_a}, b{the_b}, c{the_c}{
    }
};
int main(){
    text the_text{};//调用默认构造函数。
    text the_text_1{false, 2.0, 1};
}

如果默认构造函数被删除,则不能这么做。如:

class text{
        int a;
    double b;
    bool c;
public:
    text () = delete;
    text(bool the_c, double the_b, int the_a) : a{the_a}, b{the_b}, c{the_c}{
    }
};
int main(){
    text the_text{};//报错
}

具体原理和initializer_list有关。

posted @ 2023-02-05 15:00  bvwvd  阅读(327)  评论(0)    收藏  举报