【项目1-动物这样叫】
下面是给出的基类Animal声明和main()函数。
1、根据给出的main()函数和运行结果的提示,设计出相关的各个类,注意观察运行结果,提取出每个类中需要的数据成员,并匹配上需要的成员函数。
2、显然,Animal设计为抽象类更合适,Animal不需要能够实例化,是专门作基类使用的。改造程序,使Animal设计为抽象类,这时main()函数中p = new Animal();将出错,将此行删除。
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void cry()=0;
};
class Mouse:public Animal
{
private:
string name;
char sex;
public:
Mouse(string n,char s):name(n),sex(s){}
void cry()
{
cout<<"I am "<<name<<",I am a mouse"<<" "<<"吱,吱,吱"<<endl;
}
};
class Cat:public Animal
{
private:
string name;
char sex;
public:
Cat(string n,char s):name(n),sex(s){}
Cat(string n):name(n){}
void cry()
{
cout<<"I am "<<name<<",I am a cat"<<" "<<"喵,喵,喵"<<endl;
}
};
class Dog:public Animal
{
private:
string name;
char sex;
public:
Dog(string n,char s):name(n),sex(s){}
Dog(string n):name(n){}
void cry()
{
cout<<"I am "<<name<<",I am a dog"<<" "<<"汪,汪,汪"<<endl;
}
};
class Giraffe:public Animal
{
private:
string name;
char sex;
public:
Giraffe(string n,char s):name(n),sex(s){}
void cry()
{
cout<<"I am a giraffe ,I can not cry."<<endl;
}
};
int main( ){
Animal *p;
Mouse m1("Jerry",'m');
p=&m1;
p->cry();
Mouse m2("Jemmy",'f');
p=&m2;
p->cry();
Cat c1("Tom");
p=&c1;
p->cry();
Dog d1("Droopy");
p=&d1;
p->cry();
Giraffe g1("Gill",'m');
p=&g1;
p->cry();
return 0;
}