我鼓励这个问题: 如果我有
class A
{
public:
};
int main()
{
A a{};
A b{a};
}
gcc 给出:
moves.cc: In function ‘int main()’: moves.cc:15:7: error: too many initializers for ‘A’ A b{a};
但是当我使用 A b(a) 而不是 A b{a} 时,所有编译都正确。如果我声明默认构造函数,它也会编译。为什么会这样?
最佳答案
该类是一个聚合,因此列表初始化将执行聚合初始化,并且不会考虑隐式声明的构造函数。
因为没有数据成员,所以只有空列表可以是有效的聚合初始化器。
But when I use
A b(a)
instead ofA b{a}
all compiles correctly.
直接初始化将使用隐式构造函数而不是尝试聚合初始化。
And if I declare default constructor it compiles too.
通过声明构造函数,该类不再是聚合,只能使用构造函数进行初始化。
关于gcc 4.8.1 : list-initialization for copy constructor doesn't work 中的 C++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19112399/