#include <iostream>
#include<cstring>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
class Animal{
public:
Animal(){
name=NULL;
}
Animal(char *n){
name=strdup(n);
}
~Animal(){
delete name;
}
virtual void WhoAmI(){
cout<<"generic animal.\n";
}
protected:
char *name;
};
class Cat:public Animal{
public:
Cat():Animal(){
}
Cat(char *n):Animal(n){
}
void WhoAmI(){
cout<<"Cat: "<<name<<endl;
}
};
class Dog:public Animal{
public:
Dog():Animal(){
}
Dog(char *n):Animal(n){
}
void WhoAmI(){
cout<<"Dog: "<<name<<endl;
}
};
class Kennel{
public:
Kennel(unsigned max);
~Kennel(){
delete Residents;
}
unsigned Accept(Animal *d);
Animal * Release(unsigned pen);
void ListAnimals();
private:
unsigned MaxAnimals,NumAnimals;
Animal * * Residents;
};
Kennel::Kennel(unsigned max){
MaxAnimals=max;
NumAnimals=0;
Residents=new Animal *[MaxAnimals];
for(int i=0;i<MaxAnimals;i++){
Residents[i]=NULL;
}
}
unsigned Kennel::Accept(Animal *d){
if(NumAnimals==MaxAnimals) return 0;
++NumAnimals;
int i=0;
while(Residents[i]!=NULL) ++i;
Residents[i]=d;
return i+1;
}
Animal * Kennel::Release(unsigned pen){
if(pen>MaxAnimals){
return NULL;
}
--pen;
if(Residents[pen]!=NULL){
Animal *temp=Residents[pen];
Residents[pen]=NULL;
--NumAnimals;
return temp;
}
else return NULL;
}
void Kennel::ListAnimals(){
if(NumAnimals>0){
for(int i=0;i<MaxAnimals;i++){
if(Residents[i]!=NULL){
cout<<"The Animal in pen "<<i+1<<"is :"<<endl;
Residents[i]->WhoAmI();
}
}
}
}
Dog d1("Dad");
Dog d2("Fsdfsf");
Cat c1("bdngncb");
Cat c2("Fsd");
int main(){
Kennel K(20);
K.Accept(&d1);
K.ListAnimals();
}
C++里的宠物栏
最新推荐文章于 2022-12-21 15:29:04 发布
这篇博客展示了面向对象编程的概念,通过创建Animal、Cat和Dog类来实现不同类型的动物,并定义了Kennel类来管理这些动物。Kennel类包含了接受动物、释放动物和列出动物的功能。示例中创建了Dog和Cat实例并存入Kennel进行管理。
摘要由CSDN通过智能技术生成