gpt4 book ai didi

c++ - 如何在 C++ 类的初始化列表中初始化成员结构?

转载 作者:IT老高 更新时间:2023-10-28 14:00:00 27 4
gpt4 key购买 nike

我在 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) 在初始化列表中究竟做了什么?

或者编译器是否自动将结构初始化为零?

最佳答案

首先,您应该(必须!)阅读 c++ faq关于 POD 和聚合。在您的情况下, Foo 确实是一个 POD 类,而 foo() 是一个 值初始化 :

To value-initialize an object of type T means:

  • if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor
    for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized

所以是的,foo 将被零初始化。请注意,如果您从 Bar 构造函数中删除了此初始化,则 foo 只会是 default-initialized :

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++ - 如何在 C++ 类的初始化列表中初始化成员结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203010/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com