c++ - 初始化列表是否适用于基类?

标签 c++ initializer-list

初始化列表是否适用于基类?如果是这样,如何?例如

struct A
{
    int i;
};

struct B : public A
{
    double d;
};


int main()
{
    B b{ A(10), 3.4 };
    return 0;
}

最佳答案

标准的第 8.5.1 节定义了聚合:

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

因为 B 有一个基类,所以不是聚合:你不能在这里使用聚合大括号初始化。

编辑:

不过,您可以提供一个构造函数来进行大括号初始化(但它仍然不是聚合初始化):

struct A
{
    int i;
};

struct B : public A
{
    B(int i, double d) : A {i}, d(d) {}
    double d;
};


int main()
{
    B b { 10, 3.6 };
    return 0;
}

关于c++ - 初始化列表是否适用于基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24372236/

相关文章:

c++ - 构造函数中的 std::initializer_list 转换

c++ - boost program_options : help vs. 有意义的选项

c++ - 链接到 DLL 文件中的 Boost

c++ - 为什么我不能用统一初始化初始化初始化列表中的引用?

c++ - 是否可以将数据作为 initializer_list 传递给 std::array 结构?

c++ - 我可以对仅 move 类型的 vector 进行列表初始化吗?

c++ - 使用组合类中计算的数据构造成员类

c++ - 是否存在具有合理随机访问且从不调用元素类型的复制构造函数的 C++ 容器?

c++ - 如何制作一个深const指针

c++ - 是否可以使用 operator new 和 initialiser 语法初始化非 POD 数组?