我是 C 的新手,目前我正在研究多型性。
我有這個代碼:
#include <iostream>
class Base
{
public:
void say_hello()
{
std::cout << "I am the base object" << std::endl;
}
};
class Derived: public Base
{
public:
void say_hello()
{
std::cout << "I am the Derived object" << std::endl;
}
};
void greetings(Base& obj)
{
std::cout << "Hi there"<< std::endl;
obj.say_hello();
}
int main(int argCount, char *args[])
{
Base b;
b.say_hello();
Derived d;
d.say_hello();
greetings(b);
greetings(d);
return 0;
}
輸出在哪里:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the base object
這并沒有認識到問候函式中的多型性。
如果我將virtual關鍵字放在say_hello()函式中,這似乎按預期作業并輸出:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the Derived object
所以我的問題是:使用指標/參考時檢索多型效果?
當我看到教程時,他們會呈現如下內容:
Base* ptr = new Derived();
greetings(*ptr);
我想知道在使用多型時是否必須總是求助于指標。
對不起,如果這個問題太基本了。
uj5u.com熱心網友回復:
對于多型行為,您需要兩件事:
- 在派生類中重寫的虛擬方法
- 通過基類指標或參考訪問派生物件。
Base* ptr = new Derived();
這些都是糟糕的教程。永遠不要使用擁有原始指標和顯式新建/洗掉。改用智能指標。
uj5u.com熱心網友回復:
只需向該方法添加一個虛擬宣告,即可在使用對基類的參考時覆寫它:
virtual void say_hello() {...}
在兩個類(或至少只是基類)中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371377.html
上一篇:變數未在__attribute__((constructor))內設定或在__attribute__((constructor))呼叫后重置全域靜態變數
下一篇:C 指標函式和new關鍵字
