在面向對象程式設計(OOP)的核心支柱中,繼承無疑是實現程式碼復用與建立類別層級關係的關鍵機制。它允許我們基於現有類別(基類)定義新類別(派生類),從而避免重複撰寫資料成員與成員函式,極大地簡化了應用程式的建立與維護流程,同時也能提升執行效率。
繼承代表了經典的 is-a(是一種)關係。例如,「哺乳動物是動物」、「狗是哺乳動物」,推而廣之,「狗是動物」。在 C++ 中,當建立一個類別時,無需重新編寫所有資料成員與成員函式,只需指定新類別繼承自某個現有類別即可。被繼承的類別稱為 基類,新建立的類別稱為 派生類。
定義派生類時,我們使用類別派生列表來指定基類,語法形式如下:
class derived-class: access-specifier base-class
其中 access-specifier 可以是 public、protected 或 private,若省略則預設為 private。這個修飾符決定了基類成員在派生類中的可見性。
#include <iostream>
using namespace std;
// 基類
class Shape {
public:
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
protected:
int width;
int height;
};
// 派生類:公有繼承 Shape
class Rectangle: public Shape {
public:
int getArea() { return (width * height); }
};
int main() {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
輸出結果:
Total area: 35
派生類可以存取基類中所有非私有成員。若不想讓派生類存取某些基類成員,應在基類中將其宣告為 private。以下表格總結了不同存取層級在同一類別、派生類別與外部類別中的可見性:
| 存取權限 | public | protected | private |
|---|---|---|---|
| 同一個類別 | yes | yes | yes |
| 派生類別 | yes | yes | no |
| 外部類別 | yes | no | no |
此外,派生類不會繼承基類的建構函式、解構函式、拷貝建構函式、重載運算子以及友元函式。
繼承類型由派生列表中的存取修飾符決定,實務上幾乎只使用 public 繼承,但理解三者差異至關重要:
C++ 支援多重繼承,允許一個類別同時從多個基類繼承資料與函式。語法如下:
class Derived: inheritance1 Base1, inheritance2 Base2, ... { ... };
以下範例展示 Rectangle 同時繼承 Shape(幾何屬性)與 PaintCost(成本計算):
#include <iostream>
using namespace std;
class Shape {
public:
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
protected:
int width, height;
};
class PaintCost {
public:
int getCost(int area) { return area * 70; }
};
class Rectangle: public Shape, public PaintCost {
public:
int getArea() { return width * height; }
};
int main() {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
int area = Rect.getArea();
cout << "Total area: " << area << endl;
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
輸出結果:
Total area: 35 Total paint cost: $2450
C++ 繼承機制提供了強大的程式碼復用與多型基礎。掌握 public/protected/private 繼承的語意差異、存取控制規則,以及多重繼承的正確使用姿勢,是編寫高品質 C++ 程式的必修課。