gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:57 26 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/46096961/

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