我正在尝试以下代码:
在其中我使用指向类对象的指针调用opengascap()
汽车类,但它给出了所指向对象的函数。我的问题是为什么它给出输出“火”虽然函数名称甚至不存在于类中。car*
nuclear**
nuclear***
nuclearsubmarine
#include <iostream>
using namespace std;
class Vehicle
{
public:
virtual ~Vehicle() { }
virtual void startEngine() = 0;
};
class Car : public Vehicle
{
public:
virtual void startEngine()
{
cout<<"start car";
}
virtual void openGasCap()
{
cout<<"open";
}
};
class NuclearSubmarine : public Vehicle
{
public:
virtual void startEngine()
{
cout<<"start ship";
}
virtual void fireNuclearMissle()
{
cout<<"fire";
}
};
int main()
{
Car car;
Car* carPtr = &car;
NuclearSubmarine sub;
NuclearSubmarine* subPtr = ⊂
carPtr=(Car*)subPtr;
// This last line would have caused carPtr to point to sub !
carPtr->openGasCap(); // This might call fireNuclearMissle()!
return 0;
}
输出:火