設計架構
- 抽象基類
fruit:定義純虛函數 how_to_eat()、show_priority(),不可實例化
- 派生類
apple:紅色、1.23 元、直接食用
- 派生類
bnana (banana):黃色、0.34 元、去皮食用
- 主程式:基類指標陣列多型調用
完整程式碼
#include <iostream>
#include <string>
using namespace std;
class fruit {
public:
virtual void how_to_eat() const = 0;
virtual void show_priority() const = 0;
fruit(string a, string b, double c);
string name;
string color;
double price;
};
class apple : public fruit {
public:
apple();
void how_to_eat() const override;
void show_priority() const override;
};
class bnana : public fruit {
public:
bnana();
void how_to_eat() const override;
void show_priority() const override;
};
fruit::fruit(string a, string b, double c) : name(a), color(b), price(c) {}
apple::apple() : fruit("apple", "red", 1.23) {}
bnana::bnana() : fruit("bnana", "yellow", 0.34) {}
void apple::how_to_eat() const { cout << "直接吃" << endl; }
void apple::show_priority() const { cout << name << endl << color << endl << price << endl; }
void bnana::how_to_eat() const { cout << "去了皮再吃" << endl; }
void bnana::show_priority() const { cout << name << endl << color << endl << price << endl; }
int main() {
fruit *p[2] = {nullptr};
p[0] = new apple;
p[1] = new bnana;
for (int i = 0; i < 2; i++) {
p[i]->show_priority();
p[i]->how_to_eat();
}
// 釋放記憶體(範例簡化省略 delete)
return 0;
}
執行輸出
apple
red
1.23
直接吃
bnana
yellow
0.34
去了皮再吃
關鍵技術點
virtual ... = 0 純虛函數強制派生類實作,構成介面契約
- 基類指標/參考指向派生物件,執行期動態綁定
override 關鍵字(C++11)明確標示覆寫,編譯期檢查
- 建構子初始化清單傳遞基類參數
- 記憶體管理:
new 配對 delete,實務建議使用智慧指標