c++11 struct initialization compilation error

前端 未结 3 1322
时光说笑
时光说笑 2020-12-09 15:56
struct SS {int a; int s;};

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

The code can be compiled without any error. However, w

3条回答
  •  遥遥无期
    2020-12-09 16:04

    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.

提交回复
热议问题