C++ 调用 Struct 及其继承成员的默认构造函数

标签 c++ initialization c++14

<分区>

我希望能够在 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++17 开始,您希望的语法是有效的:

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

Live demo

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

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

关于C++ 调用 Struct 及其继承成员的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53481283/

相关文章:

c++ - 我应该为一组指针使用 std::set 或 std::unordered_set 吗?

c++ - 在 multimap 中为一个键找到两个最大值

java - 如何从主方法(或任何方法)中的args[]初始化java中的常量,例如 "public static final Integer"

c++ - 如何初始化用 auto 关键字声明的循环计数器?

c++ - auto myFunc() -> int 和 int myFunc() 的区别或好处

c++ - yaml-cpp 比较的意外结果

c++ - 在 C++ 中无效使用类?

c++ - 针对 "initialize()"方法而不是构造函数的参数

c++ - NRVO 什么时候开始?需要满足哪些要求?

c++ - 在常量表达式中更改 union 的事件成员