为什么一个结构不是空的而不是继承一个聚合结构,聚合初始化?

Why isn't a struct, empty other than inheriting an aggregate struct, aggregate-initializable?

考虑以下代码:

struct A {
    int x;
    double y;
};

struct B : public A {};

int main() {
    A a {1, 2.3}; // (*)
    B b {1, 2.3}; // (**)
}

(*)行编译,第(**)doesn't.

这是因为B不被认为是“聚合类型”吗?如果是这样,为什么不是呢?如果不是,为什么不能这样构造?

GCC 10 的默认语言版本是 C++14。在 C++14 及之前的版本中,聚合不能有任何基数 类.

原因? No good reason. 所以,从 C++17 开始,这条规则放宽了;现在没有聚合可以没有虚拟的、私有的或受保护的基础 类 …但其他的都很好。

您的代码适用于 C++17。添加 -std=c++17 到您的编译命令。


这些规则有previously been modified for C++14;请务必在提问时指明您感兴趣的语言版本。