多型意指多種形態。當類別存在繼承階層時,呼叫成員函式會根據物件實際類型執行不同函式。
未加 virtual 時,編譯器依指標宣告類型決定呼叫基類版本:
class Shape { public: int area() { cout << "Parent class area"; return 0; } };
Shape* shape = ▭ shape->area(); // 輸出 "Parent class area" (錯誤)
此為靜態多型/靜態連結/早期繫結——編譯期決定呼叫目標。
基類函式加 virtual,編譯器依指標實際指向物件決定呼叫:
class Shape { public: virtual int area() { ... } };
// 輸出 "Rectangle class area" → "Triangle class area" (正確)
此為動態連結/晚期繫結——執行期根據物件類型決定。
virtual int area() { ... })virtual int area() = 0;),構成介面契約#include <iostream>
using namespace std;
class Shape {
protected: int width, height;
public:
Shape(int a=0, int b=0) : width(a), height(b) {}
virtual int area() { cout << "Parent class area" << endl; return 0; }
};
class Rectangle : public Shape {
public:
Rectangle(int a=0, int b=0) : Shape(a,b) {}
int area() { cout << "Rectangle class area" << endl; return width * height; }
};
class Triangle : public Shape {
public:
Triangle(int a=0, int b=0) : Shape(a,b) {}
int area() { cout << "Triangle class area" << endl; return width * height / 2; }
};
int main() {
Shape* shape;
Rectangle rec(10,7); Triangle tri(10,5);
shape = &rec; shape->area(); // Rectangle class area
shape = &tri; shape->area(); // Triangle class area
return 0;
}
| 特性 | 非虛擬函式 | 虛擬函式 | 純虛擬函式 |
|---|---|---|---|
| 繫結時機 | 編譯期 (靜態) | 執行期 (動態) | 執行期 (動態) |
| 基類實作 | 必要 | 可選 | 禁止 (=0) |
| 衍生類別覆寫 | 隱藏而非覆寫 | 可選 | 強制 |
| 基類可實例化 | 是 | 是 | 否 (抽象類別) |