如何在 C++ 的初始化列表中初始化成员结构班级?
我在 C++ 中有以下类定义:
struct Foo {
int x;
char array[24];
short* y;
};
class Bar {
Bar();
int x;
Foo foo;
};
并且想在 Bar 类的初始化程序中将“foo”结构(及其所有成员)初始化为零。可以这样做吗:
Bar::Bar()
: foo(),
x(8) {
}
...?
或者 foo(x) 在初始化列表中到底做了什么?
或者该结构甚至从编译器自动初始化为零?
I have the following class definitions in c++:
struct Foo {
int x;
char array[24];
short* y;
};
class Bar {
Bar();
int x;
Foo 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) {
}
... ?
Or what exactly does the foo(x) do in the initializer list?
Or is the struct even initialized automatically to zero from the compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您应该(必须!)阅读此
所以,是的, foo 将被零初始化。请注意,如果您从
Bar
构造函数中删除此初始化,则foo
将仅是 default-initialized :First of all, you should (must !) read this c++ faq regarding POD and aggregates. In your case,
Foo
is indeed a POD class andfoo()
is a value initialization :So yes, foo will be zero-initialized. Note that if you removed this initialization from
Bar
constructor,foo
would only be default-initialized :在标准 C++ 中,您需要为 Foo 创建一个 ctor。
在 C++0x 中,您可以使用统一初始化列表,但仍然需要 Foo 的 dtor:
默认初始化
foo
(如Bar() : foo(), x(8) { }
)你需要给 Foo 一个默认的 ctor。In standard C++ you need to make a ctor for Foo.
In C++0x you may use uniform initialization list, but still you need dtor for Foo:
To default initialize
foo
(asBar() : foo(), x(8) { }
) you need to give Foo a default ctor.