Problem F: 猫、狗和公鸡的工作

该程序定义了Animal基类和Dog、Cat、Cock派生类,每个类都有构造和析构函数以及表示工作内容的work方法。Dog能看家,Cat能捉老鼠,Cock能打鸣。程序根据输入创建相应类的对象并调用work方法,最后删除对象。
摘要由CSDN通过智能技术生成

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

append.cc,

[Submit][Status]

#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;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值