c ++ 11结构初始化编译错误 [英] c++11 struct initialization compilation error

查看:136
本文介绍了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;}; 

错误:

 code>在函数'int main()':
错误:没有匹配的函数调用'SS :: SS(<大括号初始值列表>)'
v.push_back SS {1,2});
^
注意:候选项是:
注意:constexpr SS :: SS()
struct SS {int a = 0; int s = 2;};
^
注意:候选人期望有0个参数,2提供
注意:constexpr SS :: SS(const SS&)
注意:候选人期望1个参数,2提供
注意:constexpr SS :: SS(SS&&)
注意:候选人期望1个参数,2提供


<在C ++ 11中,当你在声明的时候使用非静态数据成员初始化,就像在这里:


$ b

$ b

  struct SS {int a = 0; int s = 2;}; 

您将类设为非汇总。这意味着您不能再像这样初始化一个实例:

  SS s {1,2}; 

要使此初始化语法适用于非聚合,您必须添加一个双参数构造函数:

  struct SS 
{
SS(int a,int s) ,s(s){}
int a = 0;
int s = 2;
};

此限制已在C ++ 14中取消。



注意,你可能想为类添加一个默认构造函数。用户提供的构造函数的存在会禁止编译器生成默认的构造函数。



参阅相关阅读在这里


struct SS {int a; int s;};

int main ()
{
   vector<SS> v;
   v.push_back(SS{1, 2});
}

The code can be compiled without any error. However, when the struct is initialized in class, I got compilation error. Can anyone explain it?

struct SS {int a = 0; int s = 2;};

Error:

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

解决方案

In C++11, when you use non static data member initialization at the point of declaration like you do here:

struct SS {int a = 0; int s = 2;};

you make the class a non-aggregate. This means you can no longer initialize an instance like this:

SS s{1,2};

To make this initialization syntax work for a non-aggregate, you would have to add a two-parameter constructor:

struct SS 
{
  SS(int a, int s) : a(a), s(s) {}
  int a = 0; 
  int s = 2;
};

This restriction has been lifted in C++14.

Note that you may want to add a default constructor for the class. The presence of a user-provided constructor inhibits the compiler generated default one.

See related reading here.

这篇关于c ++ 11结构初始化编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆