#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;//定义一个vehicle型指针Vp
vp=&car;//将car赋值于vp
vp->run();//run a vehicle
vp=&airplane;
vp->run();//run a vehicle
return 0;
}
第14周 阅读程序,对照结果
最新推荐文章于 2023-12-10 12:24:29 发布