阅读量:59
C++构造函数是一种特殊的成员函数,用于初始化对象的状态
- 默认构造函数:当没有为类定义任何构造函数时,编译器会自动生成一个默认构造函数。默认构造函数不接受任何参数,并且不执行任何操作。如果类中没有数据成员,那么默认构造函数什么也不做。
class MyClass {
// 编译器将自动生成一个默认构造函数
};
- 参数化构造函数:这种构造函数接受一个或多个参数,用于初始化类的数据成员。可以有多个参数化构造函数,它们具有不同的参数列表。这种情况下,编译器不会自动生成默认构造函数。
class MyClass {
public:
int x;
int y;
MyClass(int a, int b) {
x = a;
y = b;
}
};
- 拷贝构造函数:这种构造函数用于初始化一个对象,将其初始化为另一个同类型对象的副本。拷贝构造函数接受一个同类型对象的引用作为参数。
class MyClass {
public:
int x;
int y;
MyClass(const MyClass& other) {
x = other.x;
y = other.y;
}
};
- 拷贝赋值运算符:这种运算符用于将一个对象赋值给另一个同类型对象。拷贝赋值运算符接受一个同类型对象的引用作为参数。
class MyClass {
public:
int x;
int y;
MyClass& operator=(const MyClass& other) {
if (this != &other) {
x = other.x;
y = other.y;
}
return *this;
}
};
- 移动构造函数:这种构造函数用于初始化一个对象,将其初始化为另一个同类型对象的右值引用。移动构造函数接受一个同类型对象的右值引用作为参数。
class MyClass {
public:
int x;
int y;
MyClass(MyClass&& other) noexcept {
x = other.x;
y = other.y;
other.x = 0;
other.y = 0;
}
};
- 移动赋值运算符:这种运算符用于将一个对象赋值给另一个同类型对象的右值引用。移动赋值运算符接受一个同类型对象的右值引用作为参数。
class MyClass {
public:
int x;
int y;
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
x = other.x;
y = other.y;
other.x = 0;
other.y = 0;
}
return *this;
}
};
这些特殊类型的构造函数在对象创建时自动调用,以确保对象以正确的状态初始化。