YTU-OJ-Problem H: 虛擬函式練習:動物2

kewlgrl發表於2015-07-21

Problem H: 虛擬函式練習:動物2

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 425  Solved: 289
[Submit][Status][Web Board]

Description

長期的物種進化使自然界出現了生活在陸地上的陸生動物和生活在水中的水生動物。根據已有主函式編寫動物類,陸生動物類和水生動物類。

Input

動物的體長,體重,性別;

水生動物的體長,體重,性別,游泳速度;

陸生動物的體長,體重,性別,奔跑速度;

Output

動物的體長,體重,性別;

水生動物的體長,體重,性別,游泳速度;

陸生動物的體長,體重,性別,奔跑速度;

Sample Input

52 22 f
62 32 m 122
72 42 m 102

Sample Output

height:52
weight:22
sex:f
height:62
weight:32
sex:m
swimming_speed:122
height:72
weight:42
sex:m
running_speed:102

HINT

主函式已給定如下,提交時不需要包含,會自動新增到程式尾部


/*c++程式碼*/


int main()


{

        int a,b,s,r;

char c;

animal *p;

cin>>a>>b>>c;

animal pa(a,b,c);

p=&pa;

p->display();

cin>>a>>b>>c>>s;

aqu_animal pb(a,b,c,s);

p=&pb;

p->display();

cin>>a>>b>>c>>r;

ter_animal pc(a,b,c,r);

p=&pc;

p->display();

        return 0;

}

#include <iostream>
using namespace std;
class animal
{
protected:
    int height;
    int weight;
    char sex;
public:
    animal() {}
    animal(int h,int w,char s):
        height(h),weight(w),sex(s) {}
    void virtual display()
    {
        cout<<"height:"<<height<<endl;
        cout<<"weight:"<<weight<<endl;
        cout<<"sex:"<<sex<<endl;
    }
};

class aqu_animal:public animal
{
protected:
    int swimming_speed;
public:
    aqu_animal() {}
    aqu_animal(int h,int w,char s,int s_p):
        animal(h,w,s),swimming_speed(s_p) {}
    void display()
    {
        cout<<"height:"<<height<<endl;
        cout<<"weight:"<<weight<<endl;
        cout<<"sex:"<<sex<<endl;
        cout<<"swimming_speed:"<<swimming_speed<<endl;
    }
};
class ter_animal:public animal  //陸生動物
{
protected:
    int running_speed;  //游泳速度
public:
    ter_animal() {}
    ter_animal(int h,int w,char s,int r_p):
        animal(h,w,s),running_speed(r_p) {}
    void display()
    {
        cout<<"height:"<<height<<endl;
        cout<<"weight:"<<weight<<endl;
        cout<<"sex:"<<sex<<endl;
        cout<<"running_speed:"<<running_speed<<endl;
    }
};

int main()
{
    int a,b,s,r;
    char c;
    animal *p;
    cin>>a>>b>>c;
    animal pa(a,b,c);
    p=&pa;
    p->display();
    cin>>a>>b>>c>>s;
    aqu_animal pb(a,b,c,s);
    p=&pb;
    p->display();
    cin>>a>>b>>c>>r;
    ter_animal pc(a,b,c,r);
    p=&pc;
    p->display();
    return 0;
}


相關文章