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
有关。
本文来自博客园,作者:{bvwvd},转载请注明原文链接:{https://www.cnblogs.com/bvwvd/}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现