Examly題庫立即開始練習
農會 資訊管理類程式設計1056單選題

根據下列的C++語言程式碼,請問輸出結果為何? ```cpp #include <iostream> using namespace std; class CAnimal { public: void Show() { cout << " animal"; } }; class CMonkey : public CAnimal { public: void Show() { cout << " monkey"; } }; class CTiger : public CAnimal { public: virtual void Show() { cout << " tiger"; } }; int main() { CAnimal animal; CMonkey monkey; CTiger tiger; CAnimal* pAnimal[3] = { &animal, &monkey, &tiger}; for (int i=0; i<3; i++) pAnimal[i]->Show(); return 0; } ```

Aanimal animal animal正確答案
Banimal animal tiger
Canimal monkey tiger
Danimal monkey animal
答案與詳解
A
正確答案
C++多型性必須從「基類」開始宣告 virtual,本題基類未宣告,故全部靜態繫結輸出 animal。

為什麼答案是 A

基類 CAnimal 的 Show() 非虛擬函式,編譯器採用靜態繫結,透過基類指標呼叫時皆執行 CAnimal::Show()。

考點:靜態繫結考點:多型性誤區考點:多型性條件考點:指標呼叫
載入中…

想練更多程式設計考古題?

Examly 收錄 38 萬+ 道歷屆題目,每題都有像這樣的精選詳解。免費下載,立即開練。

黑皮