第十四周 项目一 --动物的叫声

来源:互联网 发布:pvf物品导入数据库 编辑:程序博客网 时间:2024/06/11 09:39
项目1】根据给出的基类Animal和main()函数。1、根据给出的main()函数和运行结果的提示,设计出相关的各个类,注意观察运行结果,提取出每个类中需要的数据成员,并匹配上需要的成员函数。2、显然,Animal设计为抽象类更合适,Animal不需要能够实例化,是专门作基类使用的。改造程序,使Animal设计为抽象类,这时main()函数中p = new Animal();将出错,将此行删除。3、每一个Animal的派生类都有一个“名字”数据成员,这一共有的成员完全可以由基类提供改造上面的程序,将这一数据成员作为抽象类Animal数据成员被各派生类使用。下面是给出的基类Animal和main()函数:class Animal{public:    virtual void cry()    {        cout<<"不知哪种动物,让我如何学叫?"<<endl;    }};int main( ){    Animal *p;    p = new Animal();    p->cry();    Mouse m1("Jerry",'m');    p=&m1;    p->cry();    Mouse m2("Jemmy",'f');    p=&m2;    p->cry();    Cat c1("Tom");    p=&c1;    p->cry();    Dog d1("Droopy");    p=&d1;    p->cry();    Giraffe g1("Gill",'m');    p=&g1;    p->cry();    return 0;}/** 程序的版权和版本声明部分* Copyright (c)2013, 烟台大学计算机学院学生* All rightsreserved.* 文件名称:* 作者:袁静* 完成日期: 2013年6月7日* 版本号: v1.0* 输入描述:无* 问题描述* 程序输出:*/#include <iostream>using namespace std;class Animal{public:    virtual void cry()    {        cout<<"不知哪种动物,让我如何学叫?"<<endl;        cout<<"                              "<<endl;    }};class Mouse :public Animal{public:    Mouse (string na,char s):name(na),sec(s) {}    void cry()    {        cout<<"我叫"<<name<<",是一只"<<((sec=='m')?"男":"女")<<";老鼠,我的叫声是吱吱"<<endl;        cout<<"                                                                     "  <<endl;    }private:    string name;    char sec;};class Cat :public Animal{private:    string name;public:    Cat (string na):name(na) {}    void cry()    {        cout<<"我叫"<<name<<",我的叫声是喵喵喵。"<<endl;        cout<<"                                  "<<endl;    }};class Dog :public Animal{public:    Dog(string na):name(na) {}    void cry()    {        cout<<"我叫"<<name<<".我是一只狗,我的叫声是汪汪汪。"<<endl;        cout<<"                                             "<<endl;    }private:    string name;};class Giraffe :public Animal{public:    Giraffe(string na,char s):name(na),sec(s) {}    void cry()    {        cout<<"我叫"<<name<<",我是一只"<<((sec=='m')?"男":"女")<<"长颈鹿,我脖子太长叫不出来。"<<endl;        cout<<"                                                                                "<<endl;    }private:    string name;    char sec;};int main( ){    Animal *p;    p = new Animal();    p->cry();    Mouse m1("Jerry",'m');    p=&m1;    p->cry();    Mouse m2("Jemmy",'f');    p=&m2;    p->cry();    Cat c1("Tom");    p=&c1;    p->cry();    Dog d1("Droopy");    p=&d1;    p->cry();    Giraffe g1("Gill",'m');    p=&g1;    p->cry();    return 0;}

原创粉丝点击