C++中的构造函数自动生成

Automatic constructor generation in C++?

本文关键字:自动生成 构造函数 C++      更新时间:2023-10-16

假设我有

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+属性的结构/类。我的问题是:有没有一种方法可以自动生成这样的构造函数?

struct Foo
{
  int a;
  std::string s;
  float f;
};
Foo f{42,"Foo",0.0};

工作得很好,但构造函数给了你更多的控制权,例如检查init值。

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

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};

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

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

在更现代的C++中,对这种语法的限制已经放宽。它被称为列表初始化

虽然我个人建议使用构造函数,因为构造函数有检查其类型参数的优势,但有一种初始化数据成员的方法,在C++11中引入,称为list-initialization,它使用用户编写的列表,自动连续分配数据成员。以下是示例结构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.