我在 C++ 中有以下类定义:
I have the following class definitions in c++:
struct Foo {
int x;
char array[24];
short* y;
};
class Bar {
Bar();
int x;
Foo foo;
};
并希望在 Bar 类的初始化程序中将foo"结构(及其所有成员)初始化为零.可以这样做吗:
and would like to initialize the "foo" struct (with all its members) to zero in the initializer of the Bar class. Can this be done this way:
Bar::Bar()
: foo(),
x(8) {
}
...?
或者 foo(x) 在初始化列表中到底做了什么?
Or what exactly does the foo(x) do in the initializer list?
或者结构体是否甚至从编译器自动初始化为零?
Or is the struct even initialized automatically to zero from the compiler?
首先,你应该(必须!)阅读这个 c++ 常见问题.在您的情况下, Foo
确实是一个 POD 类,而 foo()
是一个 值初始化 :
First of all, you should (must !) read this c++ faq regarding POD and aggregates. In your case, Foo
is indeed a POD class and foo()
is a value initialization :
值初始化一个类型的对象T 表示:
To value-initialize an object of type T means:
所以是的,foo 将被零初始化.请注意,如果您从 Bar
构造函数中删除此初始化,则 foo
将只会是 default-initialized :
So yes, foo will be zero-initialized. Note that if you removed this initialization from Bar
constructor, foo
would only be default-initialized :
如果没有指定初始化器对象,并且对象是(可能是cv 限定的)非 POD 类类型(或其数组),对象应为默认初始化;如果对象是const 限定类型,基础类类型应具有用户声明的默认构造函数.否则,如果没有初始化器为非静态对象指定,对象及其子对象,如果有的话,有一个不确定的初始价值;
If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value;
这篇关于如何在 C++ 类的初始化列表中初始化成员结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!