设计动物救助站,可以收容狗和猫。
来收养动物的,只能选最先进来的狗,或者最先进来的猫,或者不区分动物,但也必须是最先进来的那只。
#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>
#include <assert.h>
/*
动物救助站,收容狗和猫
来选动物的,只能选最先进来的,在救助站时间最长的狗或者猫,或者最长时间的狗,或者最长时间的猫
*/
using namespace std;
class Animal
{
public:
int index;
void setIdx(int idx)
{
index = idx;
}
int getIdx()
{
return index;
}
virtual void say() = 0;
virtual ~Animal(){}
};
class Dog: public Animal
{
public:
void say()
{
cout<<"owl owl"<<endl;
}
};
class Cat: public Animal
{
public:
void say()
{
cout<<"miu miu"<<endl;
}
};
class AnimaShelter
{
private:
int order;
queue<Dog *> dog_queue;
queue<Cat *> cat_queue;
public:
AnimaShelter()
{
this->order=0;
}
void enqueue(Animal* ani)
{
Dog* d = dynamic_cast<Dog *>(ani);
if(d != NULL ) // a dog
{
d->setIdx(this->order);
++this->order;
dog_queue.push(d);
}
else
{
Cat* c = dynamic_cast<Cat *>(ani);
c->setIdx(this->order);
++this->order;
cat_queue.push(c);
}
}
// choose the oldest animal
Animal* dequeAny()
{
Dog* d = dog_queue.front();
Cat* c = cat_queue.front();
if(d->getIdx() < c->getIdx())
{
dog_queue.pop();
return d;
}
else
{
cat_queue.pop();
return c;
}
}
Dog* dequeDog()
{
Dog* d = dog_queue.front();
dog_queue.pop();
return d;
}
Cat* dequeCat()
{
Cat* c = cat_queue.front();
cat_queue.pop();
return c;
}
};
int main()
{
Animal* a1 = new Dog();
Dog* d1 = dynamic_cast<Dog *>(a1);
AnimaShelter farm;
farm.enqueue(d1);
Dog* d2 = farm.dequeDog();
cout<<"Dog d2 index is "<<d2->getIdx()<<endl;
d2->say();
Cat* c1 = new Cat();
farm.enqueue(c1);
Cat* c2 = farm.dequeCat();
cout<<"Cat c2 index is "<<c2->getIdx()<<endl;
c2->say();
farm.enqueue(c2);
farm.enqueue(d2);
Animal* a2 = farm.dequeAny();
a2->say();
return 1;
}