复杂的抽象结构举例,求各高手解答
#include<iostream>using namespace std;
class Animal
{
public:
Animal(int age);
virtual ~Animal(){cout<<"析构动物..."<<endl;}
virtual int GetAge(){return itsage;}
virtual void Propagate()=0;
virtual void Sleep()=0;
virtual void Eat()=0;
virtual void Show()=0;
private:
int itsage;
};
Animal::Animal(int age):itsage(age)
{
cout<<"创建动物..."<<endl;
}
class Mammalia:public Animal
{
public:
Mammalia(int age):Animal(age){cout<<"创建哺乳动物..."<<endl;}
virtual ~Mammalia(){cout<<"析构哺乳动物..."<<endl;}
virtual void Propagate(){cout<<"哺乳动物是通过胚胎繁殖的"<<endl;}
};
class Bird:public Animal
{
public:
Bird(int age):Animal(age){cout<<"创建鸟类..."<<endl;}
virtual ~Bird(){cout<<"析构鸟类..."<<endl;}
virtual void Sleep(){cout<<"鸟类是站着睡觉"<<endl;}
virtual void Eat(){cout<<"鸟类很少是吃肉的"<<endl;}
virtual void Show(){cout<<"鸟类一般寿命为:"<<GetAge()<<"年"<<endl;}
};
class Human:public Mammalia
{
public:
Human(int age):Mammalia(age){cout<<"创建人类..."<<endl;}
virtual ~Human(){cout<<"析构人类..."<<endl;}
virtual void Sleep(){cout<<"人类是在床上睡觉的"<<endl;}
virtual void Eat(){cout<<"人类不吃生食物"<<endl;}
virtual void Show(){cout<<"人类一般寿命为:"<<GetAge()<<"年"<<endl;}
};
class Big:public Mammalia
{
public:
Big(int age):Mammalia(age){cout<<"创建猪类..."<<endl;}
virtual ~Big(){cout<<"析构猪类..."<<endl;}
virtual void Sleep(){cout<<"猪类喜欢在烂泥中睡觉"<<endl;}
virtual void Eat(){cout<<"猪类是杂食动物"<<endl;}
virtual void Show(){cout<<"由于猪会被人类宰了吃,所以猪类一般寿命为:"<<GetAge()<<"年"<<endl;}
};
int main(void)
{
Animal *p=0;
int choice=0;
bool quit=false;
while (choice<4)
{
choice=0;
cout<<"(0)退出,(1)鸟类,(2)人类,(3)猪类 :";
cin>>choice;
switch (choice)
{
case 1: p=new Bird(50); //错误全部指向这里
break;
case 2: p=new Human(80);
break;
case 3: p=new Big(1);
break;
default: quit=true;
break;
}
if (quit)
{
break;
}
p->Propagate();
p->Sleep();
p->Eat();
p->Show();
delete p;
}
return 0;
}
/*
编译时的错误:
——————————————————————————————————————————————————————————————————————
E:\c++\101复杂的抽象结构1\01.cpp(66) : error C2259: 'Bird' : cannot instantiate abstract class due to following members:
E:\c++\101复杂的抽象结构1\01.cpp(27) : see declaration of 'Bird'
E:\c++\101复杂的抽象结构1\01.cpp(66) : warning C4259: 'void __thiscall Animal::Propagate(void)' : pure virtual function was not defined
E:\c++\101复杂的抽象结构1\01.cpp(9) : see declaration of 'Propagate'
E:\c++\101复杂的抽象结构1\01.cpp(66) : error C2259: 'Bird' : cannot instantiate abstract class due to following members:
E:\c++\101复杂的抽象结构1\01.cpp(27) : see declaration of 'Bird'
E:\c++\101复杂的抽象结构1\01.cpp(66) : warning C4259: 'void __thiscall Animal::Propagate(void)' : pure virtual function was not defined
E:\c++\101复杂的抽象结构1\01.cpp(9) : see declaration of 'Propagate'
Error executing cl.exe.
01.obj - 2 error(s), 2 warning(s)
——————————————————————————————————————————————————————————————————————
*/