Description
定义Animal、Dog、Cat和Cock类,其中Animal是另外三个类的基类。定义类的构造函数和析构函数,以及work成员函数表示每种动物的工作内容。
根据题目要求和输出样例、appendcode编写程序。Dog、Cat、Cock类的work方法分别输出:
Dog can watch the house.
Cat can catch mouses.
Cock can wake people up.
Input
输入第一行是一个正整数N,表示后面有N行输入。
之后的N行,每行是一个字符串,为dog、cat或cock,用于生成对应的类的对象。
Output
见样例。
Sample Input
3 dog cat cock
Sample Output
An animal is created. A dog is created. An animal is created. A cat is created. An animal is created. A cock is created. Dog can watch the house. Cat can catch mouses. Cock can wake people up. A dog is erased. An animal is erased. A cat is erased. An animal is erased. A cock is erased. An animal is erased.
HINT
注意包含必要的STL头文件。
Append Code
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
class Animal
{
public:
virtual void work()=0;
Animal(){cout<<"An animal is created."<<endl;}
virtual~Animal(){cout<<"An animal is erased."<<endl;}
};
class Dog:virtual public Animal
{
public:
void work()
{
cout<<"Dog can watch the house."<<endl;
}
Dog(){cout<<"A dog is created."<<endl;}
~Dog(){cout<<"A dog is erased."<<endl;}
};
class Cat:virtual public Animal
{
public:
void work()
{
cout<<"Cat can catch mouses."<<endl;
}
Cat(){cout<<"A cat is created."<<endl;}
~Cat(){cout<<"A cat is erased."<<endl;}
};
class Cock:virtual public Animal
{
public:
void work()
{
cout<<"Cock can wake people up."<<endl;
}
Cock(){cout<<"A cock is created."<<endl;}
~Cock(){cout<<"A cock is erased."<<endl;}
};
int main()
{
vector<Animal*> animals;
vector<Animal*>::iterator p;
string type;
int n;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>type;
if (type=="cat")
animals.push_back(new Cat());
else if (type=="dog")
animals.push_back(new Dog());
else if (type=="cock")
animals.push_back(new Cock());
}
for(p=animals.begin(); p!=animals.end(); p++)
{
(*p)->work();
}
for(int i=0;i<n;i++)
delete animals[i];
animals.clear();
return 0;
}