自学内容网 自学内容网

C++上机实验|多态性编程练习

1.实验目的

(1)理解多态性的概念。
(2)掌握如何用虚函数实现动态联编
(3)掌握如何利用虚基类。

2.实验内容

设计一个飞机类 plane,由它派生出歼击机类fighter和轰炸机类 bomber,歼击机类fighter 和轰炸机类bomber 又共同派生出歼轰机(多用途战斗机)。利用虚函数和虚基类描述飞机类及其派生的类族。

3. 参考代码

#include <iostream>
using namespace std;
class  plane                //飞机
{
private:
double aerofoil;      //机翼
double  airframe;     //机身
double  empennage;    //尾翼
double voyage;        //航程
int  passenger;       //乘员数
public:
plane(double,double,double,double,int);
virtual void display();
};
void plane::display()
{
cout<<"\t"<<aerofoil<<"\t"<<airframe<<"\t"<<empennage<<"\t"<<voyage<<"\t"<<passenger;
}
plane::plane(double wing,double frame,double tail,double distance,int num)
{
aerofoil=wing; 
airframe=frame; 
empennage=tail; 
voyage=distance;
passenger=num;
}
class  fighter:public plane           //歼击机
{
private:
   int missile;  //导弹数
public:
   fighter(double,double,double,double,int,int);
   void fight();
   void display();
};
fighter::fighter(double wing,double frame,double tail,double distance,
            int num,int load_missile):plane(wing,frame,tail,distance,num)
{
   missile=load_missile;
}
void fighter::fight()
{ 
      cout<<"Fight!"<<endl;
}
void fighter::display()
{
   cout<<"This is a fighter!"<<endl;
   plane::display();
   cout<<"\t"<<missile<<endl;
}
class  bomber:public plane            //轰炸机
{
private:
   double bomb;       //载弹量
public:
  bomber(double, double,double,double,int,double);
  void atack();
  double getbomb();
  void display();
};
bomber::bomber(double wing,double frame,double tail,double distance, 
int num, double load_bomb):plane(wing,frame,tail,distance,num)
{
   bomb=load_bomb;
}
void bomber::atack()
{
   cout<<"Atack!"<<endl;
}
double bomber::getbomb()
{
   return bomb;
}
void bomber::display()
{
   cout<<"This is a bomber!"<<endl;
   plane::display();
   cout<<"\t"<<bomb<<endl;
}
class  fighter_bomber:virtual public fighter,virtual public bomber
 //歼轰机:多用途战斗机
{
public:
fighter_bomber(double, double,double,double,int,int,double);
void display();
};
void fighter_bomber::display()
{
   cout<<"This is a fighter_bomber!"<<endl;
   fighter::display();
   cout<<"\t"<<getbomb()<<endl;
   fight();
   atack();
}

fighter_bomber::fighter_bomber(double wing,double frame,double tail, 
double distance,int num,int load_missile,double load_bomb): fighter 
(wing,frame,tail,distance,num,load_missile),bomber(wing,frame,tail,
distance,num,load_bomb)
{ }
void 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();
}

在这里插入图片描述


原文地址:https://blog.csdn.net/benxuu/article/details/143501633

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!