我发现对类使用初始化列表语法的可能性取决于类字段是否具有默认值。为什么?
确切地说,考虑以下代码:
class S
{
public:
int a;
};
...
int a;
S s{ a };
它编译没有任何问题。但是如果我在类字段中添加一个默认值,它就会停止构建:
class S
{
public:
int a = 0;
};
...
int a;
S s{ a };
Error 1 error C2440: 'initializing' : cannot convert from 'initializer-list' to 'S'
为什么?还有什么影响这种构造函数的生成?
最佳答案
在 C++14 中,您的代码是有效的并且应该使用任何与 C++14 兼容的编译器进行编译。
在 C++11 中:
如果您没有 a
的默认值,则您的类型是聚合,因此 aggregate initialization可以执行:
An aggregate is one of the following types:
array type
class type (typically, struct or union), that has
- no private or protected non-static data members
- no user-provided constructors , including those inherited from public bases (since C++17) (explicitly defaulted or deleted constructors are allowed) (since C++11)
- no virtual, private, or protected (since C++17) base classes
- no virtual member functions
- no default member initializers (since C++11, until C++14)
一旦您为属性 a
添加了默认值,您的聚合初始化就无法再执行,因为您的类型不再是聚合。
关于c++ - 逐字段构造函数生成的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099467/