题目
定义一个车 (Vehicle) 基类,有 run、stop 等成员函数,由此派生出自行车 (Bicycle) 类、汽车 (Motorcar) 类,从 Bicycle 和 Motorcar 派生出摩托车(Motorcycle)类,它们都有run、stop 等成员函数。观察虚函数的作用。
相关阅读
完整代码
#include<bits/stdc++.h>
using namespace std;
class Vehicle{
public:
virtual void run()=0;
virtual void stop()=0;
};
class Bicycle: virtual public Vehicle{
public:
void run(){
cout << "Bicycle run !" << endl;
}
void stop(){
cout << "Bicycle stop !" << endl;
}
};
class Motorcar: virtual public Vehicle{
public:
void run(){
cout << "Motorcar run !" << endl;
}
void stop(){
cout << "Motorcar stop !" << endl;
}
};
class Motorcycle: public Bicycle, Motorcar{
public:
void run(){
cout << "Motorcycle run !" << endl;
}
void stop(){
cout << "Motorcycle stop !" << endl;
}
};
int main(){
Bicycle bicycle;
Motorcar motorcar;
Motorcycle motorcycle;
Vehicle *v[3] = {&bicycle, &motorcar, &motorcycle};
for (int i = 0; i < 3; i++) {
v[i]->run();
v[i]->stop();
}
}