实验六—虚函数与多态

54 篇文章 0 订阅
#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;
  }




    

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值