问题及代码:
#include <iostream>
using namespace std;
class Vehicle {
public:
virtual void run() const { cout << "run a vehicle. "<<endl; } //(2) run()为虚函数
};
class Car: public Vehicle //汽车
{
public:
void run() const
{ cout << "run a car. "<<endl; }
};
class Airplane: public Vehicle //飞机
{
public:
void run() const
{ cout << "run a airplane. "<<endl; }
};
int main()
{
cout<<"(a) 直接用对象访问成员函数: "<<endl;
Vehicle v;
v.run();
Car car;
Airplane airplane;
car.run();
airplane.run();
cout<<"(b)用指向基类的指针访问成员函数: "<<endl;
Vehicle *vp;
vp=&car;
vp->run();
vp=&airplane;
vp->run();
return 0;
}
运行结果:
心得体会:
当基类的函数变成虚函数时,就可以让指向基类的指针访问到派生类的数据成员