当前位置: 代码迷 >> 综合 >> 2.定义一个车(Vehicle)类,有run,stop等成员函数, 由此派生出自行车(bicycle)类、汽车(motocar)类,由bicycle类和motocar类派生出摩托车类(motocycl
  详细解决方案

2.定义一个车(Vehicle)类,有run,stop等成员函数, 由此派生出自行车(bicycle)类、汽车(motocar)类,由bicycle类和motocar类派生出摩托车类(motocycl

热度:22   发布时间:2024-01-19 08:06:01.0
#include<iostream>
using namespace std;/*
2.定义一个车(Vehicle)类,有run,stop等成员函数,
由此派生出自行车(bicycle)类、汽车(motocar)类,由bicycle类和motocar类派生出摩托车类(motocycle),
它们都run, stop等成员函数,编写相应的虚函数并测试。
*/class Vehicle {
public:virtual void run() { cout << "run  in vehicle" << endl; }virtual void stop() { cout << "stop in vehicle" << endl; }
};class Bicycle : virtual public Vehicle {
public:void run() { cout << "run  in Bicycle" << endl; }void stop() { cout << "stop in Bicycle" << endl; }
};class motocar : virtual public Vehicle {
public:void run() { cout << "run  in motocar" << endl; }void stop() { cout << "stop in motocar" << endl; }
};class Motocycle : public Bicycle, public motocar {
public:void run() { cout << "run  in motocycle" << endl; }void stop() { cout << "stop in motocycle" << endl; }
};void fun(Vehicle *p) {p->run();p->stop();
}int main() {Vehicle m1;Bicycle m2;motocar m3;Motocycle m4;fun(&m1);fun(&m2); fun(&m3); fun(&m4);getchar();return 0;
}

 

  相关解决方案