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;
}
};
这些特殊类型的构造函数在对象创建时自动调用,以确保对象以正确的状态初始化。