C++的重载、覆盖和隐藏

重载、覆盖、隐藏

1.概念

a)重载
1.相同范围(同一个类中)
2.函数名相同、参数类型不同或参数个数不同
3.virtual关键字可有可无
b)覆盖
1.不同范围(分别在基类和派生类)
2.函数名相同、参数相同
3.基类函数必须有virtual关键字
c)隐藏
1.不同范围(分别在基类和派生类)
2.如果派生类和基类函数名相同,参数不同,这时,不管基类函数有没有virtual关键字,基类函数都被隐藏
3.如果派生类和基类函数名相同,参数相同,没有virtual关键字,基类函数会被隐藏

2.例子

重载:
class Base
{
    public:
        void func(){}
        void func(int a){}
};
覆盖:
class Base
{
    public:
        virtual void func(int a){}
};

class Derived : public Base
{
    public:
        void func(int a){}
};


隐藏:
class Base
{
    public:
        void func(){}
        void func(int a){}
};

class Derived : public Base
{
    public:
        void func(int a){}
};

3.隐藏导致的陷阱

#include <iostream>
using namespace std;
class Base
{
public:
    virtual void vf(float x) { cout << "Base::vf(float) " << x << endl; }
    void g(float x) { cout << "Base::g(float) " << x << endl; }
    void h(float x) {cout << "Base::h(float) " << x << endl; }
};
class Derived : public Base
{
public:
    virtual void vf(float x) { cout << "Derived::vf(float) " << x << endl; }
    void g(int x) { cout << "Derived::g(int) " << x << endl; }
    void h(float x) { cout << "Derived::h(float) " << x << endl; }
};

int main()
{
    Derived d;
    Base *pb = &d;
    Derived *pd = &d;
    // Good : behavior depends solely on type of the object
    pb->vf(3.14); // Derived::vf(float) 3.14
    pd->vf(3.14); // Derived::vf(float) 3.14
    // Bad : behavior depends on type of the pointer
    pb->g(3.14); // Base::g(float) 3.14
    pd->g(3.14); // Derived::g(int) 3 (suprise!)
    // Bad : behavior depends on type of the pointer
    pb->h(3.14); // Base::h(float) 3.14 (suprise!)
    pd->h(3.14); // Derived::h(float) 3.14
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值