C++ 多態的核心在於「基類指針/引用指向派生類對象,調用虛函數時發生動態綁定」。本文通過一個 `Student` → `Graduate` 繼承體系,展示非虛函數與虛函數的行為差異,幫助初學者建立正確的多態認知。
#include <iostream>
#include <string>
using namespace std;
// 基類
class Student {
private:
int num;
int age;
float score;
public:
Student(int n, int a, float sc) : num(n), age(a), score(sc) {}
// 非虛函數
void display() {
cout << num << endl;
cout << age << endl;
cout << score << endl;
}
};
// 派生類
class Graduate : public Student {
private:
float pay;
public:
Graduate(int n, int a, float sc, float p) : Student(n, a, sc), pay(p) {}
// 同名函數,未加 virtual
void display() {
Student::display(); // 顯式調用基類版本
cout << pay << endl;
}
};
int main() {
Student st(12222, 22, 97.4f);
Graduate gr(353543, 26, 88.2f, 8000.0f);
Student *pt = &st;
pt->display(); // 輸出 Student 版本
pt = &gr;
pt->display(); // 注意:這裡仍輸出 Student 版本!
return 0;
}
12222 22 97.4 353543 26 88.2
| 調用方式 | 綁定時機 | 結果 |
|---|---|---|
| `pt->display()` (非虛函數) | 編譯期靜態綁定 | 永遠調用 `Student::display()`,忽略實際對象類型 |
| `pt->display()` (若加 `virtual`) | 運行期動態綁定 | 根據實際對象類型調用 `Graduate::display()` |