我希望能够在 C++14 中使用以下语法初始化一个对象:
const auto data1 = DataOne{1, 2, 3};
const auto data2 = DataTwo{1, 2, 3, 4, 5};
const auto data3 = DataThree{1, 2, 3, 4, 5, 6, 7};
这给了我以下错误消息:
error msg `error: no matching function for call to ‘DataThree::DataThree(<brace-enclosed initializer list>)’`
类型定义为:
struct DataOne
{
int a;
int b;
int c;
};
struct DataTwo : DataOne
{
int d;
int e;
};
struct DataThree : DataTwo
{
int f;
int g;
};
我不想在 struct方法中使用struct ,因为那样我将需要通过我不想使用的双点或三点来调用 params ,因为所有成员都同等重要,而且阅读起来会很糟糕。
从 C++17 开始,您想要的语法是有效的:
const auto data3 = DataThree{1, 2, 3, 4, 5, 6, 7};
在此之前,聚合初始化是非法的[dcl.init.aggr]/1
:
聚合是一个数组或类(第 9 条),没有用户提供的构造函数(12.1),没有私有或受保护的非静态数据成员(第 11 条),没有基类(第 10 条),也没有虚函数(10.3) )。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句