同一個類別可以定義多個參數列表不同的構造函數,稱為構造函數重載。這讓物件建立時能依據提供的引數選擇不同的初始化邏輯。
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle(); // 預設構造函數
Rectangle(int a, int b); // 參數化構造函數
int area() { return width * height; }
};
Rectangle::Rectangle() {
width = 5;
height = 5;
}
Rectangle::Rectangle(int a, int b) {
width = a;
height = b;
}
int main() {
Rectangle rect(3, 4); // 呼叫 Rectangle(int, int)
Rectangle rectb; // 呼叫 Rectangle()
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
Rectangle rectb;),必須顯式定義預設構造函數,否則編譯錯誤。= default 讓編譯器生成),除非刻意禁止無參數建構。const/參考成員。explicit 關鍵字避免單參數構造函數被隱式轉換使用。可在一個構造函數中呼叫另一個,減少重複程式碼:
class Rectangle {
int width, height;
public:
Rectangle() : Rectangle(5, 5) {} // 委派給雙參數版本
Rectangle(int a, int b) : width(a), height(b) {}
// ...
};