class Human {
public:
virtual string getSkinColor() = 0; // 純虛函數
};
派生 European 返回 "white",African 返回 "black"。
#include <string>
using namespace std;
class European : public Human {
public:
string getSkinColor() override { return "white"; }
};
class African : public Human {
public:
string getSkinColor() override { return "black"; }
};
override (C++11) 明確標記覆寫,編譯器會檢查簽名一致性。std::string 避免裸指針/數組生命週期問題。int main() {
Human* people[] = { new European(), new African() };
for (auto p : people) {
cout << p->getSkinColor() << endl;
delete p;
}
return 0;
}
// 輸出:
// white
// black
Human* createHuman(const string& region) {
if (region == "Europe") return new European();
if (region == "Africa") return new African();
return nullptr;
}