我只是想了解下面這段代碼,但不能理解這兩行 最後。繼承存儲地址的派生
ptr = &D;
ptr->show();
我實際上正在研究多態概念。這只是基礎知識。所以,請解釋一下它是如何工作的,以及爲什麼ptr-> show()在基地調用函數。
#include <iostream>
using namespace std;
class Base {
public:
void show()
{
cout << "This is the base\n";
}
};
class Derived : public Base {
public:
void show()
{
cout << "This is the derived\n";
}
};
int main()
{
Base B;
B.show();
Derived D;
D.show();
Base *ptr = &B;
ptr->show();
ptr = &D;
ptr->show();
return 0;
}
輸出
這是基本
這是所導出的
這是基本
這是基本
'show'需要在基地虛擬 – fizzer
是的,但我沒有正確理解它的概念我知道我會把虛擬在那裏,但你能解釋我在回答這個背後的概念和我已經問過的問題 – user3215228