简体   繁体   English

初始化 class 体内的数据成员

[英]Initializing data members inside class body

When data members should be initialized directly inside class/struct body over using constructor?何时应该使用构造函数直接在类/结构体内部初始化数据成员?

struct A{
    int x;
    A() : x{3} {}
};

struct B{
    int x{3};
};

The above two methods have the same effect.以上两种方法的效果是一样的。

Member init list must be used if the value depends on a constructor argument.如果值取决于构造函数参数,则必须使用成员初始化列表。 It must also be used if separate constructors should initialise the member with different value.如果单独的构造函数应该用不同的值初始化成员,也必须使用它。 It must also be used prior to C++11, because that is the language version where the default member initialisers were introduced.它还必须在 C++11 之前使用,因为这是引入默认成员初始化程序的语言版本。

Otherwise the choice is up to the programmer.否则选择取决于程序员。 Default member initialisers are useful for avoiding repetition in constructors that initialise with the same, constant value, as well as having more concise and simpler syntax.默认成员初始化器对于避免使用相同的常量值初始化的构造函数中的重复以及具有更简洁和更简单的语法很有用。

I would like to point out one difference.我想指出一个区别。

struct B{
    int x{3};
};

The above initialization applies to all the constructors where x is not explicitly initialized.上述初始化适用于所有未显式初始化 x 的构造函数。

The below initialization applies ONLY to the default constructor.以下初始化仅适用于默认构造函数。 So if you are following below approach, you may end up with lot of boiler plate code when the value initialized is same.因此,如果您遵循以下方法,当初始化的值相同时,您最终可能会得到很多样板代码。

struct A{
    int x;
    A() : x{3} {}
};

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

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