# 虚函数练习：动物2

``````52 22 f
62 32 m 122
72 42 m 102``````

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

``````program test(input,output);
var
h,w,v:real;
s:char;
begin
writeln('height:',h:0:0);
writeln('weight:',w:0:0);
writeln('sex:',s);
writeln('height:',h:0:0);
writeln('weight:',w:0:0);
writeln('sex:',s);
writeln('swimming_speed:',v:0:0);
writeln('height:',h:0:0);
writeln('weight:',w:0:0);
writeln('sex:',s);
writeln('running_speed:',v:0:0);
end.``````

``````#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){}
virtual void display();
};

void animal::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();
};

void aqu_animal::display()
{
animal::display();
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();
};

void ter_animal::display()
{
animal::display();
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;
}``````