C++: Where to initialize variables in constructor(C++:在构造函数中初始化变量的位置)
问题描述
可能的重复:
C++ 初始化列表
在选项 1 和选项 2 中初始化变量的优缺点是什么?
What are the pros/cons of initializing variables at option 1 vs option 2?
class MyClass
{
public:
MyClass( float f, char a );
private:
float mFloat;
char mCharacter;
bool mBoolean;
int mInteger;
};
MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ) // option 1.
{
// option 2
mCharacter = a;
mInteger = 0;
}
为什么选项 2 如此普遍?
Why is option 2 so common?
推荐答案
简而言之,只要可能,总是首选初始化列表.2个原因:
In short, always prefer initialization lists when possible. 2 reasons:
如果你没有在类的初始化列表中提到一个变量,构造函数将在进入你编写的构造函数的主体之前默认初始化它.这意味着选项 2 将导致每个变量被写入两次,一次用于默认初始化,一次用于构造函数体中的赋值.
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.
此外,正如 mwigdahl 和 avada 在其他答案中提到的,const 成员和引用成员可以仅在初始化列表中进行初始化.
Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.
还要注意,变量总是按照它们在类声明中声明的顺序进行初始化,而不是按照它们在初始化列表中列出的顺序进行初始化(如果启用了适当的警告,编译器会在列表写错时发出警告)).同样,在类的析构函数中的代码执行完毕后,析构函数将以相反的顺序调用成员析构函数,在类声明中从最后到第一个.
Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.
这篇关于C++:在构造函数中初始化变量的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:在构造函数中初始化变量的位置
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01