【C++】继承中的隐藏与覆盖

没有访问控制符时默认为私有继承

当基类中的某个函数有若干个重载版本,继承类中也实现了该函数的某个重载版本时,参数完全相同的基类版本被覆盖,基类的其他版本被隐藏

1.若要在继承类中使用基类的被覆盖方法,用::

  如B继承A, B b;   b.A::fun(); 调用的就是被覆盖的基类方法

2.若要在继承类中使用基类的被隐藏方法:

   b.A::fun(1,,2); 调用的就是被隐藏的基类方法

       在B中声明 using A::fun;

3.在私有继承的派生类中把基类的公有函数转变为公有函数

  在B中的public中声明 A::fun;  //不提倡

      在B中的public中声明 using A::fun;

#include <iostream>
using namespace std;

class A
{
public:
    void fun()
    {
        cout << "A fun()" << endl;
    }
    void fun(int x)
    {
        cout << "A fun(int x)" << endl;
    }
    void fun(int x, int y)
    {
        cout << "A fun(int x, int y)" << endl;
    }
};

class B:public A
{
public:
    void fun()  
    {
        cout << "B fun()" << endl;
        A::fun();    //在派生类中使用基类被覆盖的方法
    }
};

class C:public A
{
public:
    using A::fun;  //使用using 把A的被隐藏版本包含进来 但是被覆盖的版本无法被包含进来
    void fun()  
    {
        cout << "C fun()" << endl;
    }
};

class D:private A  //私有继承
{
public:
    using A::fun; //在私有继承时把A的公有函数改为公有
};

class E:private A  //私有继承
{
public:
    A::fun; //在私有继承时把A的公有函数改为公有(不提倡这种)
};
int main()
{
    A a;
    B b;
    C c;
    D d;
    E e;
    a.fun();       //输出A的版本
    a.fun(1);
    a.fun(1,2);
    cout << "-----------" << endl;
    b.fun();       //输出B的版本 A的版本被覆盖
    //b.fun(1);    错误,该版本被隐藏
    //b.fun(1,2);  错误,该版本被隐藏 
    cout << "-----------" << endl;
    b.A::fun();    //通过作用域运算符,得到A的版本
    b.A::fun(1);   //A的版本
    b.A::fun(1,2); //A的版本
    cout << "-----------" << endl;
    c.fun();      //C的版本
    c.fun(1);     //A的版本
    c.fun(1,2);   //A的版本
    cout << "-----------" << endl;
    d.fun();     //A的版本
    d.fun(1);    //A的版本
    d.fun(1,2);  //A的版本
    cout << "-----------" << endl;
    e.fun();     //A的版本
    e.fun(1);    //A的版本
    e.fun(1,2);  //A的版本


    return 0;
}
原文地址:https://www.cnblogs.com/dplearning/p/4784888.html