gpt4 book ai didi

c++ - 我可以在默认初始化和值初始化之间或数组的全部或部分之间进行选择吗?

转载 作者:太空狗 更新时间:2023-10-29 23:08:32 26 4
gpt4 key购买 nike

从 C++2003 开始​​,我们有值初始化和默认初始化。意思是:

struct Foo {
int i;
std :: string s;
};

Foo f1; // f1.s is default-constructed, f1.i is uninitialised
Foo f2 = Foo (); // f1.s is default-constructed, f1.i is zero

对吧?

现在假设我有这个类

class Bar : public Foo {
int n;
Foo f [SIZE];
public:
Bar ();
};

当我为 Bar 编写构造函数时,我可能想要默认或值初始化父类或 f[] 成员。我认为初始化父级的选择很简单:

Bar :: Bar () : Foo (), n (-1) {} // Parent is value-initialised (Foo::i is zero)
Bar :: Bar () : n (-1) {} // Parent is default-initialised (Foo::i is undefined)

但是 f[] 成员呢?

  • 如何默认初始化所有成员?
  • 如何对所有成员进行值初始化?
  • 如果我使用 C++11 初始化列表,如果初始化列表的大小与 SIZE 不同,会发生什么情况?

最佳答案

实际上,根据标准值初始化似乎是调用任何形式的用户定义的默认构造函数或零初始化没有默认构造函数的对象的过程(参见 8.5 [decl.init] 段落7:

To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided 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 (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.

— if T is an array type, then each element is value-initialized; — otherwise, the object is zero-initialized.

从这个意义上说,您可以使用成员初始化列表中的 f() 从 C++1998 开始对数组成员进行值初始化。如果要使用特定值,则需要将 C++2011 与初始化列表一起使用,例如f({ 1, 2, 3 })。如果参数的数量少于元素的数量,则对剩余的元素进行值初始化。实际上,它们是从一个空的初始化列表中初始化的(8.5.1 [dcl.init.aggr] 第 7 段):

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each membernot explicitly initialized shall be initialized from an empty initializer list.

...根据 8.5.4 [dcl.init.list] 第 3 段,第 7 点,从空初始化列表进行的初始化意味着:

  • Otherwise, if the initializer list has no elements, the object is value-initialized.

关于c++ - 我可以在默认初始化和值初始化之间或数组的全部或部分之间进行选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9173322/

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