#include<iostream>
#include<string.h>
#include<windows.h>
using namespace std;
class animal{ public:
animal(){}
animal(string s,string s1)
{name=s,various=s1;}
~animal(){}
void identify()
{ cout<<"The kind is "<<this->various<<endl; }
protected:
string name,various;
};
class Cat:virtual public animal{
public:
Cat() {}
Cat(string s):animal(s,"cat") {}
~Cat() {}
void identify()
{ cout<<"The kind is "<<this->various<<" ,";
cout<<"The name is "<<this->name<<endl; }
};
class Dog:public animal{
public:
Dog() {}
Dog(string s):animal(s,"dog") {}
~Dog() {}
void identify()
{ cout<<"The kind is "<<this->various<<", ";
cout<<"The name is "<<this->name<<endl; }
};
class Tiger:public Cat{
public :
Tiger() {}
Tiger(string s):animal(s,"tiger") {}
~Tiger() {}
void identify()
{ cout<<"The kind is "<<this->various<<", ";
cout<<"The name is "<<this->name<<endl; }
};
class Zoo
{ public:
Zoo() {}
Zoo(int max) //构造函数,max为最多能圈养的动物数
{this->maxanimals=max;
this->numanimals=0;
animal **residents=new animal*[maxanimals];
}
~Zoo() { delete residents ;} //析构函数
void Accept(animal *d); //接受动物
void ListAnimals() ; //显示动物园所有的动物
private:
int maxanimals ; //动物园最多能圈养的动物数
int numanimals ; //动物园当前圈养的动物数
animal **residents ; //指向动物园圈养的动物对象的指针数组
};
void Zoo::Accept(animal *d)
{ residents[numanimals++]=d;}
void Zoo::ListAnimals()
{ for(int i=0;i<numanimals;++i)
residents[i]->identify();
cout<<"The sum of Animal is "<<numanimals<<endl;
}
int main()
{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY |FOREGROUND_GREEN);//变色嘻嘻,,,,
Zoo a(10);
Cat b("wang");
b.identify();
a.Accept(&b);
Dog c("boy");
c.identify();
a.Accept(&c);
Tiger d("girl");
d.identify();
a.Accept(&d);
Tiger dd("girl");
dd.identify();
a.Accept(&dd);
Cat x("jack");
x.identify();
a.Accept(&x);
a.ListAnimals();
system("pause");
return 0;
}
实验六—虚函数与多态
最新推荐文章于 2023-11-25 21:51:16 发布