C++:成员变量的初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12170160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: Initialization of member variables
提问by madu
I have a confusion on class member variable initialization.
我对类成员变量初始化感到困惑。
Suppose in my .h file is:
假设在我的 .h 文件中是:
class Test {
int int_var_1;
float float_var_2;
public:
Test();
}
My .cpp would be:
我的 .cpp 将是:
Test::Test() : int_var_1(100), float_var_2(1.5f) {}
Now when I instantiate a class the variables get initialized to 100 and 1.5.
现在,当我实例化一个类时,变量被初始化为 100 和 1.5。
But if that is all I'm doing in my constructor, I can do the following in my .cpp:
但如果这就是我在构造函数中所做的全部,我可以在我的 .cpp 中执行以下操作:
int Test::int_var_1 = 100;
float Test::float_var_2 = 1.5f;
I'm confused as to the difference between initializing the variables in constructors or with the resolution operator.
我对在构造函数中初始化变量或使用解析运算符初始化变量之间的区别感到困惑。
Does this way of initializing variables outside constructor with scope resolution only apply to static variables or is there a way it can be done for normal variables too?
这种在具有作用域解析的构造函数之外初始化变量的方法是否仅适用于静态变量,还是有一种方法也可以用于普通变量?
回答by David Rodríguez - dribeas
You cannot substitute one for the other. If the member variables are not static, you have to use the initialization list (or the constructor body, but the initialization list is better suited)*. If the member variables are static, then you must initialize them in the definition with the syntax in the second block.
你不能用一个来代替另一个。如果成员变量不是静态的,则必须使用初始化列表(或构造函数体,但初始化列表更适合)*。如果成员变量是静态的,则必须使用第二个块中的语法在定义中初始化它们。
*Als correctly points out that in C++11 you can also provide an initializer in the declaration for non-static member variables:
*Als 正确地指出,在 C++11 中,您还可以在非静态成员变量的声明中提供初始值设定项:
class test {
int data = 5;
};
Will have data(5)
implicitly added to any initialization list where data
is not explicitly mentioned (including an implicitly defined default constructor)
将data(5)
隐式添加到任何data
未明确提及的初始化列表中(包括隐式定义的默认构造函数)
回答by Mark Garcia
You should use the first method when you are initializing non-static const
variables (at the constructor). That is the only way you can modify those kinds of member variables (unless you are using C++11).
在初始化非静态const
变量时(在构造函数中),您应该使用第一种方法。这是您可以修改这些类型的成员变量的唯一方法(除非您使用的是 C++11)。
Static member variables can be initialized by using proper scope resolution operators (outside the class).
静态成员变量可以通过使用适当的范围解析运算符(在类之外)来初始化。