[英]C++ Inheritance accessing a non-virtual function in derived class from base class pointer
[英]C++ virtual class from base pointer?
#include <iostream>
using namespace std;
class Criminal {
public:
virtual void getType() = 0;
virtual void getCrime() { cout << "Unknown" << endl; }
};
class Thug : public Criminal {
public:
void getType() { cout << "Thugging" << endl; }
void getCrime() { cout << "Gangsterism" << endl; }
};
class Tupac : public Thug {
public:
void getType() { cout << "Rapper" << endl; }
void getCrime() {
cout << "Being the best rapper to ever live" << endl;
}
};
int main() {
Criminal* tupac = new Tupac();
Criminal* thug = new Thug();
Thug* poser = new Tupac(); // Thug has no virtual function
//Criminal shouldNotCompile;
tupac->getType();
tupac->getCrime();
thug->getType();
thug->getCrime();
poser->getType(); // I intend to call Thug::getType()
poser->getCrime(); // I intend to call Thug::getCrime()
delete tupac;
delete thug;
delete poser;
getchar();
return 0;
}
輸出是
Rapper
Being the best rapper to ever live
Thugging
Gangsterism
Rapper
Being the best rapper to ever live
但是,我打算從Thug指針調用poser來打印“ Thugging”和“ Gangsterism”。
我怎樣才能做到這一點? 我希望我的代碼能按原樣工作,因為“ Thug”函數不是虛擬的,因此從Thug *指針調用的任何東西都不應該調用Thug函數嗎?
為什么我的代碼無法按預期的方式工作? 我的困惑在哪里?
什么是獲得預期行為的簡單方法?
成員函數的virtual
-ness是繼承的。 您可能尚未將Thug::getType()
聲明為virtual
,但是仍然是因為Criminal::getType()
是。 在對象繼承自Criminal
任何類型上調用getType()
仍將通過虛擬調度進行。 除非你明確指定 getType()
你想:
poser->getType(); // virtual dispatch, ends up invoking Tupac::getType()
poser->Thug::getType(); // explicitly call Thug::getType(), no dispatch
這些電話:
delete tupac;
delete thug;
delete poser;
由於“ Criminal
”的破壞者不是virtual
是危險的。 您實際上並沒有釋放所有內存或破壞所有成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.