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

时间:2016-08-02 12:41:28

标签: c++ class struct constructor code-generation

想象我有

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

所以现在当我需要创建新的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;
       }
    }

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

4 个答案:

答案 0 :(得分:9)

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

Foo f{42,"Foo",0.0};

工作正常,但构造函数可以提供更多控制,例如检查初始值。

答案 1 :(得分: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){
   }
};

如果你不想手动操作(手动选项肯定更好,更可控),你可以使用它:

struct Foo
{
  int a;
  std::string s;
  float f;
  //The default constructor is exist by default here
};
Foo obj{0,"",0.0f};

答案 2 :(得分:1)

如果你的结构是POD,你可以使用{}来初始化它们。

struct A {
  int a;
  int b;
} foo = {2,3};

在更现代的C ++中,放宽了对此语法的限制。它被称为list initialization

答案 3 :(得分:1)

虽然我个人建议使用构造函数,因为构造函数具有检查其类型参数的优势,但是对于错误,有一种初始化数据成员的方法,在list-initialization中引入,称为{{1} },它使用用户编写的列表,连续自动分配数据成员。以下是示例结构foo

的示例
struct Foo
{
    int a;
    int b;
};
int main()
{
    Foo bar {27,86}; // Note the use of curly braces here to initialize the list. There is
                     // no range or error checking, but a and b are consecutively initialized
    return 0;
}

如果你没有在代码中阅读我的评论,那么它是: 请注意这里使用花括号来初始化列表。没有范围或错误检查,但a和b连续初始化

如果我的编译器不支持C ++ 11怎么办?

如果编译器不支持C ++ 11,Uniform Initialization(一直是C ++中的一个功能)会派上用场。以下是相同结构Foo的示例:

Foo baz = {22,33}; //Note the '=' sign here, that separates it from list-initialization.