简体   繁体   English

C ++:成员变量的初始化

[英]C++: Initialization of member variables

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? 这种使用范围分辨率在构造函数外部初始化变量的方法是否仅适用于静态变量,或者是否也可以对常规变量执行此操作?

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任何初始化列表中(包括隐式定义的默认构造函数)

You should use the first method when you are initializing non-static const variables (at the constructor). 在初始化非静态const变量时(在构造函数中),应该使用第一种方法。 That is the only way you can modify those kinds of member variables (unless you are using C++11). 这是您可以修改这些类型的成员变量的唯一方法(除非您使用的是C ++ 11)。

Static member variables can be initialized by using proper scope resolution operators (outside the class). 可以使用适当的范围解析运算符(类外)初始化静态成员变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM