重载重写_覆盖重定义隐藏.cpp

  1. //首先先给出定义吧
    //重载:同一个类中,函数名相同但是参数不同,不管是否有virtual关键字。
    //重定义:不同类中(特指基类和子类)函数名相同。但是参数列表和返回值不一定相同。
    //重写(覆盖):基类函数有virtual关键字,且函数名、参数列表、返回值都相同。属于重定义一种。
    //名字隐藏:如果对基类的某一成员函数的版本在子类中重定义,那么基类中该函数的版本将被隐藏。
    //看个小程序。


    #include <iostream>
    #include <string>
    using namespace std;


    class Base {
    public:
        virtual void mf1()    
        {
            cout << "Base::virtual void mf1()" << endl;
        }
        virtual void mf1(int)        //重载mf1() virtual函数
        {
            cout << "Base::virtual void mf1(int)" << endl;
        }
        int f() const
        {
            cout << "Base::f()\n";
            return 1;
        }
        int f(string) const        //重载f()函数
        {
            cout << "Base::f(string)" << endl;
            return 1;
        }
    };


    class Derived : public Base {
    public:
        using Base::f;        //使用using关键字让f()函数可见
        virtual void mf1()    // 重写基类虚函数
        {
            cout << "Derived::virtual void mf1()" << endl;
        }
        int f(int)    //重定义f()函数, 可以改变其参数列表
        {
            cout << "Derived::f(int) const\n";
    return 1;
        }
    };




    class Derived2 : public Base {
    public:
        void f()    //重定义f()函数, 可以改变其返回值
        {
            cout << "Derived2::f() const\n";
        }
    };


    int main()
    {
        Derived d;
        Derived2 d2;
        int x = 10;
        string str = "hello";
        
        
        d.mf1();        ///调用派生类中的函数
    //!    d.mf1(x);        ///派生类重写了基类中的mf1虚函数,则基类中其他版本的函数都被隐藏了
        d.f(x);            ///调用派生类中的函数
        d.f();
        
        d2.f();
    //!    d2.f(str);        ///派生类重定义基类中的f函数,则基类中其他版本的函数都被隐藏了
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值