寵物的生長(多態)


現在要開發一個系統,對寵物的生長狀態進行管理。 給出下面的一個基類框架 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 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 class Pet      //Pet類 抽象類 6 {
 7 protected:
 8     string name;
 9     int length,weight,current;
10 public:
11     virtual void display(int day)=0;  //虛函數 
12     virtual ~Pet(){};
13 };
14 
15 class Cat:public Pet
16 {
17 public:
18     Cat(){};
19     Cat(string N,int L,int W,int C);
20     void display(int day);
21 };
22 
23 Cat::Cat(string N,int L,int W,int C)  //初始化Cat類對象
24 {
25     name=N,length=L,weight=W,current=C;
26 }
27 
28 void Cat::display(int day)  //重載虛函數
29 {
30     cout<<name<<" "<<length+(day-current)<<" "<<weight+(day-current)*2<<endl;
31 }
32 
33 class Dog:public Pet
34 {
35 public:
36     Dog(){};
37     Dog(string N,int L,int W,int C);
38     void display(int day);
39 };
40 
41 Dog::Dog(string N,int L,int W,int C)  //初始化Dog類對象
42 {
43     name=N,length=L,weight=W,current=C;
44 }
45 
46 void Dog::display(int day)
47 {
48     cout<<name<<" "<<length+(day-current)*2<<" "<<weight+(day-current)<<endl;
49 }
50 
51 int main()
52 {
53     int flag,i(0);
54     Pet *pt[10];
55     string name;
56     int length,weight,time;
57     while(cin>>flag,flag==1||flag==2)  //輸入flag,當flag==1或==2時執行
58     {
59         cin>>name>>length>>weight>>time;
60         switch(flag)
61         {
62         case 1:pt[i++]=new Cat(name,length,weight,time);break;
63         case 2:pt[i++]=new Dog(name,length,weight,time);break;
64         }
65     }
66     for(int j(0);j<i;j++)
67     {
68         pt[j]->display(flag);
69     }
70     return 0;
71 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM