c++11 struct初始化编译错误

标签 c++ c++11

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/

相关文章:

c++ - 内联成员运算符与内联运算符 C++

c++ - 使用 _mm_load_pd 时函数崩溃

c++ - 为什么static_cast转换无效?

c++ - 将成员函数传递给没有地址的 std::thread

c++ - 从 C++11 中的容器元组中提取 value_type 的元组

c++ - 声明内联函数 noexcept 有意义吗?

c++ - 重载 operator<<(ostream&, T) 其中 T 是 "enum class MyEnum"

c++ - 有时可以在 C++ 中使用 std::atomic 代替 std::mutex 吗?

C++插入排序中位数计算错误

c++ - 在其他模板中使用 Any 类(类似于 boost::any)