C++ OJ习题练习(十二)设计飞机类Plane及其派生类

Problem Description

设计一个飞机Plane类,由它派生出歼击机Fighter类和轰炸机Bomber类,歼击机Fighter类和轰炸机Bomber类又共同派生出歼轰机(多用途战斗机)Fighter_Bomber类。虚基类描述飞机类及其派生的类族。

#include<iostream>
using namespace std;
class Plane    //飞机类
{
private:
    float wing;        //机翼长度
    float body;        //机身长度
    float tail;        //尾翼长度
    float voyage;      //航程
    int guest;         //旅客人数
public:
    Plane(float,float,float,float,int);    
    void display();
};
void Plane::display()
{
    cout<<"Plane:\twing:"<<wing<<" body:"<<body<<" tail:"<<tail<<" voyage:"<<voyage<<" guest:"<<guest;
}
Plane::Plane(float w,float b,float t,float v,int n)
{
    wing=w;
    body=b;
    tail=t;
    voyage=v;
    guest=n;
}
//你的代码将被嵌在这里

int main()
{    
    Fighter f(10.0,6.0,2.5,1800,1,8);             //歼击机
    f.display();
    Bomber b(30,9,6,12000,12,6000);             //轰炸机
    b.display();
    Fighter_Bomber fb(20,7,3.2,4000,2,6,2500);    //歼轰机
    fb.display();   
    return 0;
}

Sample Output

This is a fighter!
Plane:	wing:10 body:6 tail:2.5 voyage:1800 guest:1
missile:8
This is a bomber!
Plane:	wing:30 body:9 tail:6 voyage:12000 guest:12
bomb:6000
This is a fighter_bomber!
This is a fighter!
Plane:	wing:20 body:7 tail:3.2 voyage:4000 guest:2
missile:6
bomb:2500
Fight!
Attack!

Hint

1、Plane类有数据成员:wing(机翼长度),body(机身长度),tail(尾翼长度),voyage(航程),guest(旅客人数);成员函数display,用于显示数据成员的值;
2、Fighter类(歼击机类)有新的数据成员missile(导弹数),重定义了display函数,新定义了fight函数(输出字符串“Fight!”);
3、Bomber类(轰炸机类)有新的数据成员bomb(载弹量),重定义display函数,新定义attack函数(输出字符串“Attack!”)、getbomb函数。
4、Fighter_Bomber类(歼轰机类), 重定义了display函数。
5、Plane类(飞机类)为虚基类。

解题代码

class Fighter:public Plane{
protected:
    int missile;
public:
    Fighter(float w,float b,float t,float v,int n,int Missile):Plane(w,b,t,v,n),missile(Missile){}
    void display()
    {
        cout << "This is a fighter!\n";
        Plane::display();
        cout << "\nmissile:" << missile << endl;
    }
    void fight(){cout << "Fight!\n";}
};

class Bomber:public Plane{
protected:
    int bomb;
public:
    Bomber(float w,float b,float t,float v,int n,int bom):Plane(w,b,t,v,n),bomb(bom){}
    void display()
    {
        cout << "This is a bomber!\n";
        Plane::display();
        cout << "\nbomb:" << bomb << endl;
    }
    void attack(){cout << "Attack!\n";}
};

class Fighter_Bomber:public Fighter,Bomber{
public:
    Fighter_Bomber(float w,float b,float t,float v,int n,int Missile,int bom):Fighter(w,b,t,v,n,Missile),Bomber(w,b,t,v,n,bom){}
    void display()
    {
        cout << "This is a fighter_bomber!\n";
        Fighter::display();
        cout << "bomb:" << bomb << endl;
        Fighter::fight();
        Bomber::attack();
    }
};

©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页