C ++:成员变量的初始化 [英] C++: Initialization of member variables

查看:147
本文介绍了C ++:成员变量的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对类成员变量初始化有困惑。



假设我的.h文件是:

  class Test {

int int_var_1;
float float_var_2;

public:
Test();
}

我的.cpp将是:

  Test :: Test():int_var_1(100),float_var_2(1.5f){} 

现在当我实例化一个类时,变量被初始化为100和1.5。



但是如果这是我所有在我的构造函数中,我可以在我的.cpp中执行以下操作:

  int Test :: int_var_1 = 100; 
float Test :: float_var_2 = 1.5f;

我对初始化构造函数中的变量或解析运算符之间的区别感到困惑。 / p>

这种在构造函数之外初始化变量的方法只适用于静态变量,还是有一种方法可以对普通变量执行?

解决方案

你不能用一个替换另一个。如果成员变量不是静态的,则必须使用初始化列表(或构造函数体,但初始化列表更合适) * 。如果成员变量是静态的,则必须在定义中使用第二个块中的语法初始化它们。



* 在C ++ 11中,你也可以在非静态成员变量的声明中提供一个初始化器:

  class test {
int data = 5;
};

将会有 data(5)没有明确提及(包括隐式定义的默认构造函数) data 的任何初始化列表


I have a confusion on class member variable initialization.

Suppose in my .h file is:

class Test {

int int_var_1;
float float_var_2;

public:
       Test();
}

My .cpp would be:

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.

But if that is all I'm doing in my constructor, I can do the following in my .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:

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)

这篇关于C ++:成员变量的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆