虚函数和多态_3
描述
定义了一个基类Animal,它包含两个私有数据成员,一个是string成员,存储动物的名称(“Fido”),一个是整数成 weight,存储了动物的重量(单位是千克)。该基类还包含一个公共的虚拟成员函数who()和一个纯虚函数sound(),公共的虚拟成员函数who()返回一个string对象,该对象包含了Animal对象的名称和重量,纯虚函数sound()在派生类中应返回一个string对象,表示该动物发出的声音。把Animal类作为一个公共基类,派生三个类Sheep(“Baaaa!!”)、Dog(“woof woof!!”),Cow(“Mooooo!!!”),在每个类中实现sound()函数。定义一个类Zoo,它可以在一个数组中存储3种不同类型的动物(使用指针数组,数组元素0存储Sheep类的指针,1存储Dog类的指针,2存储Cow类指针。)。编写一个main()函数函数,创建给定数量的派生类对象的随机序列,在Zoo对象中存储这些对象(使用指针数组)。
输入
动物类别(0,1,2。0表示Sheep,1:Dog,2:Cow),动物名字,动物重量
输出
按编号顺序依次输出动物名字和动物重量
样例输入
2 cow 100
0 duoli 50
1 jiji 3
样例输出
I’m a sheep. My name is duoli. My weight is 50 Kgs. Baaaa!!
I’m a dog. My name is jiji. My weight is 3 Kgs. woof woof!!
I’m a cow. My name is cow. My weight is 100 Kgs. Mooooo!!!
代码
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Animal
{
string name;
int weight;
public:
void set(string a,int b);
string getn();
int getw();
virtual string who();
virtual string sound()=0;
virtual void js();
};
void Animal::set(string a,int b){name = a; weight = b;}
string Animal::getn(){return name;}
int Animal::getw(){return weight;}
string Animal::who()
{
stringstream ss;
ss<<getw();
string s1 = ss.str();
return string("My name is ")+getn()+string(". My weight is ")+s1+string(" Kgs. ");
}
void Animal::js(){cout<<"zl";}
class sheep:public Animal
{
public:
void sets(string a,int b);
string who();
string sound();
void js();
};
void sheep::sets(string a,int b){set(a,b);}
string sheep::who()
{
stringstream ss;
ss<<getw();
string s1 = ss.str();
return string("My name is ")+getn()+string(". My weight is ")+s1+string(" Kgs. ");
}
string sheep::sound()
{return "Baaaa!!";}
void sheep::js()
{cout << "I'm a sheep. ";}
class dog:public Animal
{
public:
void setd(string a,int b);
string who();
string sound();
void js();
};
void dog::setd(string a,int b){set(a,b);}
string dog::who()
{
stringstream ss;
ss<<getw();
string s1 = ss.str();
return string("My name is ")+getn()+string(". My weight is ")+s1+string(" Kgs. ");
}
string dog::sound()
{return "woof woof!!";}
void dog::js()
{cout << "I'm a dog. ";}
class cow:public Animal
{
public:
void setc(string a,int b);
string who();
string sound();
void js();
};
void cow::setc(string a,int b){set(a,b);}
string cow::who()
{
stringstream ss;
ss<<getw();
string s1 = ss.str();
return string("My name is ")+getn()+string(". My weight is ")+s1+string(" Kgs. ");
}
string cow::sound()
{return "Mooooo!!!";}
void cow::js()
{cout << "I'm a cow. ";}
class zoo
{
public:
zoo(){};
Animal *p[3];
sheep a;
dog b;
cow c;
void setz();
};
void zoo::setz()
{
p[0] = &a;
p[1] = &b;
p[2] = &c;
}
int main()
{
int x;
string y;
int z;
zoo T;
for(int i = 1; i <= 3; i++)
{
cin >> x >> y >> z;
if(x==0)
T.a.sets(y,z);
if(x==1)
T.b.setd(y,z);
if(x==2)
T.c.setc(y,z);
}
T.setz();
for(int i = 0; i <= 2 ;i++)
{
T.p[i]->js();
cout << (T.p[i]->who());
cout << (T.p[i]->sound());
cout << endl;
}
return 0;
}