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.
这篇关于在构造函数中初始化字段 - 初始化列表与构造函数主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在构造函数中初始化字段 - 初始化列表与构造函数主体


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01