如何在C ++类的初始化器列表中初始化成员结构? [英] How to initialize member-struct in initializer list of C++ class?

查看:185
本文介绍了如何在C ++类的初始化器列表中初始化成员结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中有以下类定义:

  struct Foo {
int x;
char array [24];
short * y;
};

class Bar {
Bar();

int x;
Foo foo;
};

并且想在初始化器中初始化foostruct(及其所有成员)的Bar类。可以这样做:

  Bar :: Bar()
:foo(),
x (8){
}

...?



或者在初始化器列表中 foo(x)做什么?



首先,你应该(必须)读这个 c ++ faq 关于POD和聚合。在你的case, Foo 确实是一个POD类, foo()是一个值初始化


要初始化类型
的对象T意味着:


$ b b

  • 如果T是具有用户声明的构造函数(12.1)的类类型(子句9),则调用T的默认构造函数

    如果T没有可访问的默认构造函数);

  • 如果T是非联合类类型,没有用户声明的构造函数,则每个非静态数据成员和base-

  • 如果T是数组类型,则每个元素都是值初始化的;
  • ,对象是零初始化

初始化。请注意,如果您从 Bar 构造函数中删除此初始化,则 foo 只能是 >:


如果没有为
对象指定初始值设定项,且对象为(可能为
cv-合格的)非POD类类型(或其
数组),对象应为
默认初始化;如果对象是
的const限定类型,
底层类类型应该有一个
用户声明的默认构造函数。
否则,如果没有为非静态对象指定初始值为

对象及其子对象(如果有),
有一个不确定的初始值
;



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?

解决方案

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 :

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

So yes, foo will be zero-initialized. Note that if you removed this initialization from Bar constructor, foo would only be 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 ++类的初始化器列表中初始化成员结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆