在C++中生成自动构造函数?

DEL*_*A12 1 c++ constructor struct code-generation class

想象我有

struct Foo
{
   int a;
   string s;
   float f;
}
Run Code Online (Sandbox Code Playgroud)

所以现在当我需要创建新的Foo时,我需要添加一个构造函数:

struct Foo
    {
       int a;
       string s;
       float f;
       Foo(int a, string s, float f)
       {
          this->a = a;
          this->s = s;
          this->f = f;
       }
    }
Run Code Online (Sandbox Code Playgroud)

但是,这种手动编写构造函数的方法非常耗时,尤其是对于具有10+属性的结构/类.我的问题是:有没有办法自动生成这样的构造函数?

And*_*rsK 9

struct Foo
{
  int a;
  std::string s;
  float f;
};

Foo f{42,"Foo",0.0};
Run Code Online (Sandbox Code Playgroud)

工作正常,但构造函数为您提供更多控制,例如检查初始值.


Hum*_*awi 5

首先,如果你想自己编写构造函数,最好这样做:

struct Foo
{
   int a;
   string s;
   float f;
   Foo()=default;// this is needed if Foo needs to be default constructable (Thanks to @ NathanOliver)
   Foo(int a, string s, float f):a(a),s(s),f(f){
   }
};
Run Code Online (Sandbox Code Playgroud)

如果您不想手动执行(手动选项肯定更好,更可控),您可以使用:

struct Foo
{
  int a;
  std::string s;
  float f;
  //The default constructor is exist by default here
};
Foo obj{0,"",0.0f};
Run Code Online (Sandbox Code Playgroud)