抽象宠物类的实现 代码参考

2022-10-08,,,

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class pet
 7 {
 8     private:
 9         string name;
10         int age;
11         string color;
12     public:
13         pet(string name,int age,string color)
14         {
15             this->name=name;
16             this->age=age;
17             this->color=color;
18         }
19         string getname(){return name;}
20         int getage(){return age;}
21         string getcolor(){return color;}
22         virtual void speak();
23         virtual void getinfo();
24 };
25 
26 void pet::speak()
27 {
28     cout<<"how does a pet speak?"<<endl;
29     return;
30 }
31 
32 void pet::getinfo()
33 {
34     cout<<"名字:"<<name<<endl;
35     cout<<"年龄:"<<age<<endl;
36     cout<<"颜色:"<<color<<endl;
37 }
38 
39 class cat:public pet
40 {
41     public:
42         cat(string name, int age, string color):pet(name,age,color){}
43         void speak();
44         void getinfo();
45 };
46 
47 void cat::speak()
48 {
49     cout<<"猫的叫声:miao!miao!"<<endl;
50     return;
51 }
52 
53 void cat::getinfo()
54 {
55     cout<<"猫的名字:"<<getname()<<endl;
56     cout<<"猫的年龄:"<<getage()<<endl;
57     cout<<"猫的颜色:"<<getcolor()<<endl;
58     return;
59 }
60 
61 class dog:public pet
62 {
63     public:
64         dog(string name, int age, string color):pet(name,age,color){}
65         void speak();
66         void getinfo();
67 };
68 
69 void dog::speak()
70 {
71     cout<<"狗的叫声:wang!wang!"<<endl;
72     return;
73 }
74 
75 void dog::getinfo()
76 {
77     cout<<"狗的名字:"<<getname()<<endl;
78     cout<<"狗的年龄:"<<getage()<<endl;
79     cout<<"狗的颜色:"<<getcolor()<<endl;
80     return;
81 }
82 
83 int main()
84 {
85     string name1,name2,color1,color2;
86     int age1,age2;
87     cin>>name1>>age1>>color1;
88     cin>>name2>>age2>>color2;
89     pet *p1,*p2;
90     p1=new cat(name1,age1,color1);
91     p2=new dog(name2,age2,color2);
92     p1->getinfo();
93     p1->speak();
94     p2->getinfo();
95     p2->speak();
96     return 0;
97 }

 

《抽象宠物类的实现 代码参考.doc》

下载本文的Word格式文档,以方便收藏与打印。