gpt4 book ai didi

c++ - 您可以使用带有指定初始值设定项的显式构造函数吗?

转载 作者:行者123 更新时间:2023-12-04 01:05:31 24 4
gpt4 key购买 nike

下面代码中,成员b的初始化是否合法?

class B {
public:
explicit B(int) {}
};

struct A {
B b;
};

class C {
public:
C() : a{.b{33}} {}

A a;
};

使用最新版本的 gcc 编译会出现此错误 (wandbox)

prog.cc: In constructor 'C::C()':
prog.cc:12:11: error: converting to 'B' from initializer list would use explicit constructor 'B::B(int)'
12 | C() : a{.b{33}} {}
| ^~~~~~~~~

但是最新版本的 clang 可以很好地编译代码(wandbox)

哪个编译器是正确的?

最佳答案

这是一个 gcc 错误(已提交 99566)。

规则,来自[dcl.init.aggr]/4.2 , 是:

Otherwise, the element is copy-initialized from the corresponding initializer-clause or is initialized with the brace-or-equal-initializer of the corresponding designated-initializer-clause.

元素 (b) 应该从大括号或相等初始化器 ({33}) 初始化。完全没问题,那不是复制初始化。 gcc 接受 B b{33},同样的事情应该发生在这里。

关于c++ - 您可以使用带有指定初始值设定项的显式构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66606143/

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