现在要开发一个系统,对宠物的生长状态进行管理。 给出下面的一个基类框架 class Pet { protected: string name;//姓名 int length;//身长 int weight;//体重 int current;//当前日期 public: virtual void display(int day)=0;//输出目标日期的身长和体重 } 以Pet为基类,构建出Cat和Dog两个类: Cat一天身长加1,体重加2。 Dog一天身长加2,体重加1。 生成上述类并编写主函数,要求主函数中有一个基类Pet指针数组,数组元素不超过10个。 Pet *pt[10]; 主函数根据输入的信息,相应建立Cat类对象或Dog类对象,并给出目标日期宠物的身长和体重。
提示:应用虚函数实现多态
输入格式:每个测试用例占一行,每行给出宠物的基本信息,第一个为当前宠物的类型:1为Cat,2为Dog。接下来为它的名字,随后的两个数字为身长和体重,最后为测身长和体重的日期(不大于10的正整数)。最后一行为目标日期(大于10的正整数)
输出格式:输出目标日期宠物姓名、身长和体重
输入样例:1 Marry 22 12 5
2 Jack 10 9 9
1 Jim 11 8 6
11
输出样例:Marry 28 24
Jack 14 11
Jim 16 18
实现代码如下:
#include<iostream>
#include<string>
using namespace std;
class Pet{
protected:
string name;
int length;
int weight;
int current;
public:
Pet(){
name="";
length=0;
weight=0;
current=0;
}
virtual void display(int day)=0;
};
class Cat:public Pet{
public:
Cat(string n,int l,int w,int c){
name=n;
length=l;
weight=w;
current=c;
}
void display(int day){
cout<<name<<" "<<length+day-current<<" "<<weight+(day-current)*2<<endl;
}
};
class Dog:public Pet{
public:
Dog(string n,int l,int w,int c){
name=n;
length=l;
weight=w;
current=c;
}
void display(int day){
cout<<name<<" "<<length+(day-current)*2<<" "<<weight+day-current<<endl;
}
};
int main(){
string name;
Pet *p[10];
int length,weight,current,day,x,count=0,i;
while(1){
cin>>x;
if(x>10){
for(i=0;i<count;i++)
p[i]->display(x);
break;
}
cin>>name>>length>>weight>>current;
if(x==1)
p[count]=new Cat(name,length,weight,current);
else
p[count]=new Dog(name,length,weight,current);
count++;
}
}