struct SS {int a; int s;};
int main ()
{
vector<SS> v;
v.push_back(SS{1, 2});
}
代码可以编译没有任何错误。但是,当在类中初始化结构时,出现编译错误。谁能解释一下?
struct SS {int a = 0; int s = 2;};
错误:
In function ‘int main()’:
error: no matching function for call to ‘SS::SS(<brace-enclosed initializer list>)’
v.push_back(SS{1, 2});
^
note: candidates are:
note: constexpr SS::SS()
struct SS {int a = 0; int s = 2;};
^
note: candidate expects 0 arguments, 2 provided
note: constexpr SS::SS(const SS&)
note: candidate expects 1 argument, 2 provided
note: constexpr SS::SS(SS&&)
note: candidate expects 1 argument, 2 provided
最佳答案
在 C++11 中,当您像在此处一样在声明点使用非静态数据成员初始化时:
struct SS {int a = 0; int s = 2;};
您将类(class)设为非聚合。这意味着您不能再像这样初始化实例:
SS s{1,2};
要使这种初始化语法适用于非聚合,您必须添加一个双参数构造函数:
struct SS
{
SS(int a, int s) : a(a), s(s) {}
int a = 0;
int s = 2;
};
此限制已在 C++14 中解除。
请注意,您可能希望为该类添加一个默认构造函数。用户提供的构造函数的存在会禁止编译器生成默认构造函数。
见相关阅读here .
关于c++11 struct初始化编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18184096/