实验9:Problem B: 动物类-抽象类
最坑的一点:狗的量词是条!条!条!
Home | Web Board | ProblemSet | Standing | Status | Statistics |
Problem B: 动物类-抽象类
Submit: 1567 Solved: 774
[Submit][Status][Web Board]
[Submit][Status][Web Board]
Problem B: 动物类-抽象类
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1567 Solved: 774
[Submit][Status][Web Board]
Description
每种动物都有自己的叫声,如狗的叫声是"汪汪汪",猫的叫声是"喵喵喵",老鼠的叫声是"吱吱吱"。
构造类Animal,Dog,Cat,Mouse,他们都有成员数据name和sex,表示名字和性别。一个成员函数cry(),输出他们的叫声,在main函数中采用多态性调用他们。
Input
动物的姓名和性别
Output
动物的信息
Sample Input
Jerry m
Jemmy f
Tom m
Droopy m
Sample Output
我叫Jerry,是一只男老鼠,我的叫声是:吱吱吱!
我叫Jemmy,是一只女老鼠,我的叫声是:吱吱吱!
我叫Tom,是一只男猫,我的叫声是:喵喵喵!
我叫Droopy,是一条男狗,我的叫声是:汪汪汪!
HINT
Animal应当为抽象类。
Append Code
#include<iostream> using namespace std; class Animal{ public: string name; char sex; ///Animal(string n,char m){name=n;sex=m;if(sex=='m') cout<<"我叫"<<name<<",是一只男"; else cout<<"我叫"<<name<<",是一只女";} virtual void cry()=0; }; class Mouse:public Animal{ public: string name; char sex; Mouse(string n,char m){name=n;sex=m;if(sex=='m') cout<<"我叫"<<name<<",是一只男"; else cout<<"我叫"<<name<<",是一只女";} void cry(){cout<<"老鼠,我的叫声是:吱吱吱!"<<endl;} }; class Dog:public Animal{ public: string name; char sex; Dog(string n,char m){name=n;sex=m;if(sex=='m') cout<<"我叫"<<name<<",是一条男"; else cout<<"我叫"<<name<<",是一条女";} void cry(){cout<<"狗,我的叫声是:汪汪汪!"<<endl;} }; class Cat:public Animal{ public: string name; char sex; Cat(string n,char m){name=n;sex=m;if(sex=='m') cout<<"我叫"<<name<<",是一只男"; else cout<<"我叫"<<name<<",是一只女";} void cry(){cout<<"猫,我的叫声是:喵喵喵!"<<endl;} }; int main( ) { string nam; char s; cin>>nam>>s; Animal *p; Mouse m1(nam, s); p=&m1; p->cry(); cin>>nam>>s; Mouse m2(nam, s); p=&m2; p->cry(); cin>>nam>>s; Cat c1(nam, s); p=&c1; p->cry(); cin>>nam>>s; Dog d1(nam, s); p=&d1; p->cry(); return 0; }
向代码最深处出发~!