[英]Initializing class members with {}
Someone gave me (part of) the following code:有人给了我(部分)以下代码:
struct MyStruct
{
int x = {};
int y = {};
};
I never saw this syntax before, what does initialization with {}
mean?我以前从未见过这种语法,用{}
进行初始化是什么意思?
This is default member initializer (since C++11),这是默认成员初始值设定项(C++11 起),
Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.通过默认成员初始值设定项,它是包含在成员声明中的大括号或等号初始值设定项,并且在构造函数的成员初始值设定项列表中省略该成员时使用。
The initialization itself is copy-list-initialization (since C++11), as the effect, the data member x
and y
would be value-initialized (and zero-initialized as built-in type) to 0
.初始化本身是 复制列表初始化(自 C++11 起),因此数据成员x
和y
将值初始化(并且作为内置类型初始化为零)为0
。
Since the C++11 standard there are two ways to initialize member variables:由于 C++11 标准有两种方法来初始化成员变量:
Using the constructor initialization list as "usual":像“通常”一样使用构造函数初始化列表:
struct Foo { int x; Foo(): x(0) { } };
Use the new inline initialization where members are getting their "default" values using normal initialization syntax:使用新的内联初始化,其中成员使用正常初始化语法获取其“默认”值:
struct Foo { int x = 0; };
Both these ways are for many values and types equivalent.这两种方式对于许多值和类型都是等效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.