【C++OJ多重继承与虚拟继承】交通工具(多重继承)
题目描述
1、建立如下的类继承结构:
1)一个车类CVehicle作为基类,具有max_speed、speed、weight等数据成员,display()等成员函数
2)从CVehicle类派生出自行车类CBicycle,添加属性:高度height
3)从CVehicle类派生出汽车类CMotocar,添加属性:座位数seat_num
4)从CBicycle和CMotocar派生出摩托车类CMotocycle
2、分别定义以上类的构造函数、输出函数display及其他函数(如需要)。
3、在主函数中定义各种类的对象,并测试之,通过对象调用display函数产生输出。
输入
第一行:最高速度 速度 重量
第二行:高度
第三行:座位数
输出
第一行:Vehicle
第二行及以后各行:格式见Sample
输入样例
100 60 20
28
2
输出样例
Vehicle:
max_speed:100
speed:60
weight:20Bicycle:
max_speed:100
speed:60
weight:20
height:28Motocar:
max_speed:100
speed:60
weight:20
seat_num:2Motocycle:
max_speed:100
speed:60
weight:20
height:28
seat_num:2
参考代码
#include <iostream>
#include <string>
using namespace std;
class CVehicle //车类CVehicle作为基类
{
protected: //具有max_speed、speed、weight等数据成员
double max_speed;
double speed;
double weight;
public:
CVehicle(double m, double s, double w) : max_speed(m), speed(s), weight(w) {} //初始化参数列表
void display() //输出函数
{
cout << "max_speed:" << max_speed << endl
<< "speed:" << speed << endl
<< "weight:" << weight << endl;
}
};
class CBicycle : virtual public CVehicle //从CVehicle类派生出自行车类CBicycle
{
protected:
double height; //添加属性:高度height
public:
CBicycle(double m, double s, double w, double h) : CVehicle(m, s, w), height(h) {} //初始化参数列表
void display() //打印函数
{
cout << "height:" << height << endl;
}
};
class CMotocar : virtual public CVehicle //从CVehicle类派生出汽车类CMotocar
{
protected:
int seat_num; //添加属性:座位数seat_num
public:
CMotocar(double m, double s, double w, int seat) : CVehicle(m, s, w), seat_num(seat) {}
void display()
{
cout << "seat_num:" << seat_num << endl;
}
};
class CMotocycle : public CBicycle, public CMotocar //从CBicycle和CMotocar派生出摩托车类CMotocycle
{
public:
CMotocycle(double m, double s, double w, double h, int seat)
: CVehicle(m, s, w), CBicycle(m, s, w, h), CMotocar(m, s, w, seat) {} //构造函数,初始化参数列表
};
int main()
{
double m, s, w, h;
int seat;
cin >> m >> s >> w; //第一行:最高速度 速度 重量
CVehicle v1(m, s, w); //
cout << "Vehicle:" << endl;
v1.display();
cout << endl;
cin >> h; //第二行:高度
CBicycle b1(m, s, w, h);
cout << "Bicycle:" << endl;
b1.CVehicle::display();
b1.display();
cout << endl;
cin >> seat; //第三行:座位数
CMotocar m1(m, s, w, seat);
cout << "Motocar:" << endl;
m1.CVehicle::display();
m1.display();
cout << endl;
CMotocycle m2(m, s, w, h, seat);
cout << "Motocycle:" << endl;
m2.CVehicle::display();
m2.CBicycle::display();
m2.CMotocar::display();
return 0;
}