现在的位置: 首页 > 综合 > 正文

猫叫狗不叫,虚函数继承

2013年12月02日 ⁄ 综合 ⁄ 共 1284字 ⁄ 字号 评论关闭
/*1、根据给出的main()函数和运行结果的提示,设计出相关的各个类,注意观察运行结果,提取出
每个类中需要的数据成员,并匹配上需要的成员函数。
2、显然,Animal 设计为抽象类更合适,Animal 不需要能够实例化,是专门作基类使用的。改造
程序,使Animal 设计为抽象类,这时main()函数中p = new Animal();将出错,将此行删除。
3、每一个Animal 的派生类都有一个“名字”数据成员,这一共有的成员完全可以由基类提供改
造上面的程序,将这一数据成员作为抽象类Animal 数据成员被各派生类使用。*/
#include <iostream>
#include<string >
using namespace std;

class Animal
{
public:
    Animal(string d):s(d) {}
    virtual void cry()
    {
        cout<<"不知哪种动物,让我如何学叫? "<<endl;
    }
protected:
    string s;
};
class Mouse:public Animal//老鼠类
{
public:
    Mouse(string s,string se/*性别*/):Animal(s)
    {
        sex=se;
    }
    void cry()
    {
        cout<<"我叫"<<s<<",是一只";
        if(sex=="m")
            cout<<"男";
        else
            cout<<"母";
        cout<<"老鼠,我的叫声是:吱吱吱。"<<endl;
    }

    string sex;
};
class Cat: public Animal//猫类
{
public:
    Cat(string s):Animal(s) {}
    void cry()
    {
        cout<<"我是一只猫,我的名字是:"<<s<<",我的叫声是:喵喵喵。"<<endl;
    }
};
class Dog:public Animal//狗类
{
public:
    Dog(string s):Animal(s) {}
    void cry()
    {
        cout<<"我是一条狗,我的名字是:"<<s<<",我的叫声是:旺旺旺。"<<endl;
    }
};
class Giraffe:virtual public Animal//长颈鹿类
{
public:
    Giraffe(string s,string se):Animal(s)
    {
        sex=se;
    }
    void cry()
    {
        cout<<"我是"<<s<<",是";
        if(sex=="m")
        {
            cout<<"男";
        }
        else
            cout<<"母";
        cout<<"长颈鹿,我的脖子太长,我发不出声音来!~"<<endl;
    }
protected:
    string sex;//性别
};
int main( )
{
    Animal *p;
    Animal m("dsa");
    p=&m;
    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;
}

【上篇】
【下篇】

抱歉!评论已关闭.