Initializing fields in constructor - initializer list vs constructor body(在构造函数中初始化字段 - 初始化列表与构造函数主体)
问题描述
我使用 C++ 已经有一段时间了,但我不确定
I have been working in c++ for some time now, but I am unsure about the difference between
public : Thing(int _foo, int _bar): member1(_foo), member2(_bar){}
和
public : Thing(int _foo, int _bar){
member1 = _foo;
member2 = _bar;
}
我感觉它们做同样的事情,但这两种语法之间是否存在实际差异.其中一个比另一个更安全吗,它们是否以不同的方式处理默认参数.
I have a feeling that they do the same thing, but is there a practical difference between these 2 syntaxes. Is one of these safer then the other, and do they handle default parameters differently.
对第一个例子不太习惯,所以如果我犯了错误,我道歉.
Not totally accustomed to the first example so if I made a mistake on it I apologize.
推荐答案
如果 member1
和 member2
是非 POD(即非Plain Old Data) 类型:
They are not the same if member1
and member2
are non-POD (i.e. non-Plain Old Data) types:
public : Thing(int _foo, int _bar){
member1 = _foo;
member2 = _bar;
}
相当于
public : Thing(int _foo, int _bar) : member1(), member2(){
member1 = _foo;
member2 = _bar;
}
因为它们会在构造函数体开始执行之前被初始化,所以基本上完成了两倍的工作.这也意味着,如果这些成员的类型没有默认构造函数,那么您的代码将不会编译.
because they will be initialized before the constructor body starts executing, so basically twice the work is done. That also means, if the type of these members don't have default constructor, then your code will not compile.
这篇关于在构造函数中初始化字段 - 初始化列表与构造函数主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在构造函数中初始化字段 - 初始化列表与构造函数主体


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01