c++什么时候应该在成员变量定义的时候直接赋值而不是构造函数赋初值?
怪我咯
怪我咯 2017-04-17 13:30:47
0
5
550
class A {
public:
    int _a = 2; //直接赋值
    A(){}
}

什么情况下应该这样赋值,什么情况下应该在构造函数里赋值?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(5)
刘奇
class A {
public:
    int _a = 2; // 类内初始化
    A(){}
}

This way of writing is the same as

class A {
public:
    int _a;
    A() : _a(2) {}  // 构造函数初始化列表
}

The effect is the same. The process of assigning initial values ​​will occur in the member initialization phase of the constructor. The former is just syntactic sugar added by C++11. In this way, if a class has multiple constructors and the initial value of a member is the same in these constructors, then the initial value can be set through in-class initialization to reduce duplication of work.

Peter_Zhu

In-place initialization ("direct assignment") is better, concise and clear

迷茫

I guess you want to assign _a to 2 when each class is initialized, right?
In this case, just write int _a = 2 into the default constructor of A.

A(){_a = 2;}

Or do you want multiple instances of a class to share one _a variable?
In this case you should use the static keyword

static int _a;

Also pay attention to access permissions

刘奇

In-place initialization

This is more convenient because you can use type var=? or type var{} assignment directly when declaring, which can get rid of the trouble of writing a constructor for initialization, but this requires the latest c++11 standard, compared to Initialization list, you no longer need to adjust the order of variables in the initialization list in order to get rid of the compiler's warning that the initialization and declaration order are inconsistent (which is sometimes very dangerous).

struct Init
{
    int x = 11;
    int z {10};
};

Initialization list

The initialization list is a very "old" initialization method. It has obvious advantages over in-place initialization. It does not require any new feature support. All versions of C++ can support it. Another advantage is that it can be used委托构造 (c++11).

struct InitList
{
    InitList()
        :InitList(10, 11)
    {}
    
    InitList(int x, int z)
        :x(x)
        ,z(z)
    {}
    
    int x;
    int z;
};

As for what to use is a matter of personal preference, the initialization list is more general, and currently the two can also be used together.

Note: When a member exists in both the initialization list and in-place initialization, the initialization list will be executed first, and the in-place initialization will be ignored.

左手右手慢动作

The initial value within the class will be transcribed into the constructor
So there is no difference
Since the initialization order of members with the initial value within the class will still be in the default order, I recommend not writing a class Internal initial value

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!