[英]Aggregate initialization of a class that privately inherits an aggregate class in C++11
Consider the following code: 考虑以下代码:
struct base
{
int x, y, z;
};
struct derived : private base
{
using base::base;
};
int main(int argc, const char *argv[])
{
base b{1, 2, 3}; // Allowed
derived d{1, 2, 3}; // Not allowed
}
The line derived d{1, 2, 3};
这条线
derived d{1, 2, 3};
makes my compiler (Clang 3.3) fail with error "no matching constructor for initialization of 'derived'". 使我的编译器(Clang 3.3)失败,并显示错误“初始化“派生”时没有匹配的构造函数”。 Why is this?
为什么是这样? Is there any way to initialize
derived
via aggregate initialization? 有没有办法通过聚合初始化
derived
初始化?
derived
has a base class, so it's not an aggregate (§8.5.1/1: "An aggregate is an array or a class (Clause 9) with [...] no base classes [...]"). derived
有一个基类,因此它不是一个聚合(第8.5.1 / 1节:“聚合是没有基类[...]的数组或类(第9条)”)。
Since it's not an aggregate, it can't be initialized with aggregate initialization. 由于它不是聚合,因此无法使用聚合初始化进行初始化。
The most obvious workaround would probably be to add a ctor
to base, and have the ctor for derived
pass arguments through to base
: 最明显的解决方法可能是在base中添加一个
ctor
,并将derived
pass参数的ctor传递到base
:
struct base
{
int x, y, z;
base(int x, int y, int z) : x(x), y(y), z(z) {}
};
struct derived : private base
{
derived(int a, int b, int c) : base(a, b, c) {}
};
int main(int argc, const char *argv[])
{
base b{1, 2, 3}; // Allowed
derived d{1, 2, 3}; // Allowed
}
Of course, that doesn't work if you're set on base
remaining an aggregate. 当然,如果您是以剩余总和为
base
设置的话,这是行不通的。
Edit: For the edited question, I don't see a way to use an std::initializer_list
here -- std::array
doesn't have anything to accept an initializer_list
. 编辑:对于已编辑的问题,我在这里看不到使用
std::initializer_list
std::array
没有任何东西可以接受initializer_list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.