[英]Using initializer lists through inheritance
有没有办法使用初始化列表来初始化Bar?
struct Foo {
int i[2];
};
struct Bar : Foo {};
Foo f{0, 1}; // OK
Bar b{0, 1}; // error: no matching function for call to
// ‘Bar::Bar(< brace-enclosed initializer list>)’
由于Foo
是一种聚合类型,它是通过aggregate initialization
,它不支持从c ++ 14开始的基类初始化。 但好消息是它将在c ++ 17中得到支持:)
从cppreference中获取的示例:
// aggregate
struct base1 { int b1, b2 = 42; };
// non-aggregate
struct base2 {
base2() : b3(42) {}
int b3;
};
// aggregate in C++17
struct derived : base1, base2 { int d; };
derived d1{ {1, 2}, { }, 4}; // d1.b1 = 1, d1.b2 = 2, d1.b3 = 42, d1.d = 4
derived d2{ { }, { }, 4}; // d2.b1 = 0, d2.b2 = 42, d2.b3 = 42, d2.d = 4
它编译,但使用C ++ 17聚合可以有基类。 这允许基本数据成员的列表初始化。 看到这里更多:
http://en.cppreference.com/w/cpp/language/aggregate_initialization
聚合初始化的效果是:
每个直接公共库(自C ++ 17)数组元素或非静态类成员,按照类定义中的数组下标/外观的顺序,从初始化列表的相应子句进行复制初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.