题目描述
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>
using namespace std;
class CVehicle{
protected:
int max_speed;
int speed;
int weight;
public:
CVehicle(){}
CVehicle(int m,int s,int w){
max_speed=m;
speed=s;
weight=w;
}
void displayCVehicle(){
cout<<"Vehicle:"<<endl;
cout<<"max_speed:"<<max_speed<<endl;
cout<<"speed:"<<speed<<endl;
cout<<"weight:"<<weight<<endl;
}
};
class CBicycle:public CVehicle{
protected:
int height;
public:
CBicycle(int m,int s,int w,int h):CVehicle(m,s,w),height(h){}
void displayCBicycle(){
cout<<"Bicycle:"<<endl;
cout<<"max_speed:"<<max_speed<<endl;
cout<<"speed:"<<speed<<endl;
cout<<"weight:"<<weight<<endl;
cout<<"height:"<<height<<endl;
}
};
class CMotocar:public CVehicle{
protected:
int seat_num;
public:
CMotocar(int m,int s,int w,int s_n):CVehicle(m,s,w),seat_num(s_n){}
void displayCMotocar(){
cout<<"Motocar:"<<endl;
cout<<"max_speed:"<<max_speed<<endl;
cout<<"speed:"<<speed<<endl;
cout<<"weight:"<<weight<<endl;
cout<<"seat_num:"<<seat_num<<endl;
}
};
class CMotocycle:public CMotocar,public CBicycle{
public:
CMotocycle(int m,int s,int w,int h,int s_n):CMotocar(m,s,w,s_n),CBicycle(m,s,w,h){}
void displayCMotocycle(){
cout<<"Motocycle:"<<endl;
cout<<"max_speed:"<<CMotocar::max_speed<<endl;//详细见下文
cout<<"speed:"<<CMotocar::speed<<endl;
cout<<"weight:"<<CMotocar::weight<<endl;
cout<<"height:"<<CBicycle::height<<endl;
cout<<"seat_num:"<<CMotocar::seat_num<<endl;
}
};
int main(){
int m_s,s,w,h,s_n;
cin>>m_s>>s>>w>>h>>s_n;
CVehicle c1(m_s,s,w);
c1.displayCVehicle();
cout<<endl;
CBicycle c2(m_s,s,w,h);
c2.displayCBicycle();
cout<<endl;
CMotocar c3(m_s,s,w,s_n);
c3.displayCMotocar();
cout<<endl;
CMotocycle c4(m_s,s,w,h,s_n);
c4.displayCMotocycle();
}
Motocycle类继承了Motocar和Bicycle类,这两个父类同时拥有max_speed,speed,weight的数据成员,如果直接输出则分不清是Motocar还是Bicycle类的数据成员,需要告诉计算机具体的范围