C++構(gòu)造函數(shù)是一種特殊的成員函數(shù),用于初始化對象的狀態(tài)
class MyClass {
// 編譯器將自動生成一個默認(rèn)構(gòu)造函數(shù)
};
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;
}
};
這些特殊類型的構(gòu)造函數(shù)在對象創(chuàng)建時自動調(diào)用,以確保對象以正確的狀態(tài)初始化。