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;
}
};
這些特殊類型的構造函數在對象創建時自動調用,以確保對象以正確的狀態初始化。