zoukankan      html  css  js  c++  java
  • 继承和多类的基础(C++)

    代码一:

    #include <iostream>
    using namespace std;


    class Fish
    {
    public:
    bool isFreshWaterFish;

    void Swim()
    {
    if (isFreshWaterFish)
    cout << "Swims in lake" << endl;
    else
    cout << "Swims in sea" << endl;
    }
    };

    class Tuna: public Fish
    {
    public:
    Tuna()
    {
    isFreshWaterFish = false;
    }
    };

    class Carp: public Fish
    {
    public:
    Carp()
    {
    isFreshWaterFish = true;
    }
    };

    int main()
    {
    Carp myLunch;
    Tuna myDinner;

    cout << "Getting my food to swim" << endl;

    cout << "Lunch: ";
    myLunch.Swim();

    cout << "Dinner: ";
    myDinner.Swim();

    return 0;
    }

    通过公有继承,Tuna和Carp类将暴露基类共有方法swim

    代码二:

    #include <iostream>
    using namespace std;

    class Fish
    {
    public:
    void Swim()
    {
    cout << "Fish swims!" << endl;
    }
    };

    class Tuna:public Fish
    {
    public:
    // override Fish::Swim
    void Swim()
    {
    cout << "Tuna swims!" << endl;
    }
    };

    void MakeFishSwim(Fish& InputFish)
    {
    // calling Fish::Swim
    InputFish.Swim();
    }

    int main()
    {
    Tuna myDinner;

    // calling Tuna::Swim
    myDinner.Swim();

    // sending Tuna as Fish
    MakeFishSwim(myDinner);

    return 0;
    }

    其中void MakeFishSwim(Fish& InputFish)将传入都看作Fish基类

    代码三:

    class Fish
    {
    public:
    virtual void swim()
    {
    cout <<"Fish swim!!!"<<endl;
    }
    };
    class Tuna :public Fish
    {
    public:
    void swim()
    {
    cout << "Tuna swim in the sea" << endl;

    }
    };

    class Carp :public Fish
    {
    public:
    void swim()
    {
    cout << "Carp can swim in the lake" << endl;
    }
    };

    void MakeFishSwim(Fish&inputFish)
    {
    //
    inputFish.swim();

    }
    int main()
    {
    Carp myLunch;
    Tuna myDinner;

    MakeFishSwim(myDinner);
    MakeFishSwim(myLunch);

    system("pause");
    return 0;

    }

    其中virtual 虚函数的优先级在派生类之后,这是典型的降级

  • 相关阅读:
    selenium iframe 定位 qq空间说说
    单个 进程网速 消耗 网路 带宽
    网页加速
    baidu 验证网站 一一映射
    内容原发网站seo不重视2个标签,导致seo效果不如转发网站
    vi shell 的水平 决定了 手机shell 办公的效率
    键盘控制鼠标
    seo 谷歌去年悄然收购这家英国硬件公司
    视频 爬虫
    python 深浅 拷贝
  • 原文地址:https://www.cnblogs.com/1994xlai/p/11911908.html
Copyright © 2011-2022 走看看