#include <iostream>
using namespace std;
class Vehicle //交通工具
{
public:
void run() const
{
cout << "run a vehicle. "<<endl;
}
};
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();//输出;run a vehicle.
Car car;
Airplane airplane;
car.run();//输出;run a car.
airplane.run();//输出;run a airplane.
cout<<"(b)用指向基类的指针访问成员函数: "<<endl;
Vehicle *vp;//指向基类
vp=&car;
vp->run();//输出;run a vehicle.
vp=&airplane;
vp->run();//输出;run a vehicle.
return 0;
}
所以可以看出:当基类的指针指向派生类时,用指针调用同名成员函数,执行的是基类的成员函数