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 @   bvwvd  阅读(297)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示