#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
但是我打算从暴徒的指针中打电话来打印“Thugging”和“Gangsterism”。
我该怎么做?我希望我的代码按原样运行,因为“Thug”函数不是虚函数,所以不应该从Thug *指针调用任何调用Thug函数的东西吗?
为什么我的代码不按照我的预期方式工作?我的困惑在哪里?
什么是实现我的预期行为的简单方法?
答案 0 :(得分:4)
virtual
- 继承成员函数。您可能没有将Thug::getType()
声明为virtual
,但仍然是因为Criminal::getType()
。在对象继承自getType()
的任何类型上调用Criminal
仍将通过虚拟调度。除非您明确指定 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
,很危险。你实际上没有释放所有内存或摧毁所有成员。