【问题标题】:C++ Call default constructor for Struct and its inherited members [duplicate]C ++调用Struct及其继承成员的默认构造函数[重复]
【发布时间】:2018-11-26 12:37:31
【问题描述】:

我希望能够在 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 in struct 方法,因为那样我将需要通过我不想使用的双点或三点来调用参数,因为所有成员都同等重要,而且看起来不好读。

【问题讨论】:

标签: c++ initialization c++14


【解决方案1】:

从 C++17 开始,您希望的语法是有效的:

const auto data3 = DataThree{1, 2, 3, 4, 5, 6, 7};

Live demo

在此之前,根据[dcl.init.aggr]/1,聚合初始化将是非法的:

聚合是一个数组或类(第 9 条),没有用户提供的构造函数 (12.1),没有私有或受保护的非静态数据成员(第 11 条),没有基类(第 10 条),并且没有虚函数(10.3)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2016-12-05
    相关资源
    最近更新 更多