虚继承(animal)

描述

长期的物种进化使两栖动物既能活跃在陆地上,又能游动于水中。利用虚基类建立一个类的多重继承,包括动物(animal,属性有体长,体重和性别),陆生动物(ter_animal,属性增加了奔跑速度),水生动物(aqu_animal,属性增加了游泳速度)和两栖动物(amp_animal)。其中两栖动物保留了陆生动物和水生动物的属性。

要求: animal只有带参的构造函数。其他函数根据需要自行设置

 

输入

两栖动物的体长,体重,性别,游泳速度,奔跑速度(running_speed)

输出

初始化的两栖动物的体长,体重,性别,游泳速度,奔跑速度(running_speed)和输入的两栖动物的体长,体重,性别,游泳速度,奔跑速度(running_speed)

样例输入

52
22
f
102
122

样例输出

height:52
weight:22
sex:f
swimming_speed:102
running_speed:122

 

//#pragma GCC optimize(2)
#include <iostream>
using namespace std;
class animal
{
protected:
    int high;
    int wigh;
    char sex;
public:
    animal(int a,int b,char c):high(a),wigh(b),sex(c){}
};
class ter:virtual public animal
{
protected:
    int speed;
public:
    ter(int a=0,int b=0,char c='\0',int d=0):animal(a,b,c),speed(d){}
};
class aqu:virtual public animal
{
protected:
    int speed;
public:
    aqu(int a,int b,char c,int d):animal(a,b,c),speed(d){}
};
class amp:public aqu,public ter
{
public:
    //虚基类中只定义一个带形参的构造函数,则间接或直接的派生类的构造函数都要对虚基类初始化
    amp(int a=0,int b=0,char c=0,int x=0,int y=0):animal(a,b,c),aqu(a,b,c,x)//,ter(a,b,c,y)
    {
    }
    friend ostream &operator<<(ostream &out,amp &obj)
    {
        out<<"height:"<<obj.high<<endl;
        out<<"weight:"<<obj.wigh<<endl;
        out<<"sex:"<<obj.sex<<endl;
        out<<"swimming_speed:"<<obj.aqu::speed<<endl;
        out<<"running_speed:"<<obj.ter::speed<<endl;
    }
    friend istream &operator>>(istream &in,amp &obj)
    {
        in>>obj.high>>obj.wigh>>obj.sex>>obj.aqu::speed>>obj.ter::speed;
    }
};
int main()
{
    amp a;
    cin>>a;
    cout<<a;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章