gpt4 book ai didi

c++ - 为什么我不能大括号初始化从另一个结构派生的结构?

转载 作者:IT老高 更新时间:2023-10-28 12:34:39 25 4
gpt4 key购买 nike

当我运行这段代码时:

struct X {
int a;
};

struct Y : public X {};

X x = {0};
Y Y = {0};

我明白了:

error: could not convert ‘{0}’ from ‘<brace-enclosed initializer list>’ to ‘Y’

为什么大括号初始化适用于基类而不适用于派生类?

最佳答案

对 C++17 之前的 C++ 标准版本的回答:

您的问题与 aggregate initialization 有关: struct X 是一个聚合,而 struct Y 不是。这是关于聚合 (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).

这个子句指定如果一个 class 有一个基类,那么它不是一个聚合。这里,struct Ystruct X 作为基类,因此不能是聚合类型。

关于您遇到的特定问题,请从标准中获取以下条款:

When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order. Each member is copy-initialized from the corresponding initializer-clause. If the initializer-clause is an expression and a narrowing conversion (8.5.4) is required to convert the expression, the program is ill-formed.

当您执行X x = {0} 时,聚合初始化用于将a 初始化为0。但是,当您执行 Y y = {0} 时,由于 struct Y 不是聚合类型,编译器会寻找合适的构造函数。由于没有一个隐式生成的构造函数(默认、复制和移动)可以对单个整数执行任何操作,因此编译器会拒绝您的代码。


关于此构造函数查找,来自 clang++ 的错误消息更明确地说明了编译器实际尝试执行的操作 (online example):

Y Y = {0};
^ ~~~

main.cpp:5:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'int' to 'const Y &' for 1st argument

struct Y : public X {};
^

main.cpp:5:8: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'int' to 'Y &&' for 1st argument

struct Y : public X {};
^

main.cpp:5:8: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 1 was provided

注意有a proposal扩展聚合初始化以支持您的用例,并且它已进入 C++17。如果我阅读正确,它会使您的示例在您期望的语义下有效。所以...您只需要等待符合 C++17 的编译器即可。

关于c++ - 为什么我不能大括号初始化从另一个结构派生的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16983539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com