C++中的构造函数自动生成
Automatic constructor generation in C++?
假设我有
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.
相关文章:
- 我可以说服自动生成的构造函数将我的 POD 类成员归零吗?
- 删除了所有自动生成的构造函数/运算符的类仍然可以从函数返回吗
- Visual Studio在创建类时不再生成构造函数/解构器
- c++ 17 中结构自动定义构造函数的规则是什么?
- C++自动生成的具有常量和非常量引用的复制构造函数
- 移动构造函数是自动生成的,即使成员没有移动构造函数?
- 如何避免丢失自动生成的初始化列表构造函数
- 为什么 c++ 实例在通过 Objective-c 类调用时会自动调用构造函数和析构函数?
- 如果我默认复制构造函数,将生成构造函数和移动分配
- 自动生成的移动构造函数导致非法行为
- 自动生成移动构造函数
- 为什么在以下情况下,c++会生成构造函数
- 自动移动构造函数
- C++自动生成带有用户声明析构函数的移动构造函数
- 需要c++默认构造函数,而不是已经用参数生成构造函数
- 在c++ 11中,当类没有任何构造函数时,自动生成类成员函数
- move构造函数是自动生成的
- 编译器自动确定构造函数初始化列表
- 自动生成带有不可移动成员的移动构造函数
- 编译器生成构造函数来初始化成员