派生类隐藏基类同名方法

问题描述

我正在阅读this文章,并指出

这称为Derived :: f(complex)。为什么?好吧,请记住 派生未声明“使用Base:f;”,因此很明显Base :: f(int) 和Base :: f(double)无法调用

我决定尝试使用此代码

class Base {
public:
    virtual void f( int ) {
        cout << "Base::f(int)" << endl;
    }

    virtual void f( double ) {
        cout << "Base::f(double)" << endl;
    }

    virtual void g( int i = 10 ) {
        cout << i << endl;
    }
};

class Derived: public Base {
    using Base::f;
    
public:
    void f( complex<double> ) {
        cout << "Derived::f(complex)" << endl;
    }

    void g( int i = 20 ) {
        cout << "Derived::g() " << i << endl;
    }
};


int main() {
    Derived d;

    d.f(1.0);        
}

我得到了错误 main.cpp:在函数'int main()'中:

main.cpp:43:16: error: 'virtual void Base::f(double)' is inaccessible within this context
   43 |         d.f(1.0);

我的问题是如何使用using Base::f;以及如何解决此问题?

解决方法

简单。您应该在类的公共部分下编写“使用”声明,如下所示。如果将声明放在private部分中,则Base函数可用于Derived类,但它们将成为Derived类的私有成员。这就是为什么您的编译器会引发“无法访问”错误。

#include <iostream>
#include <complex>

using namespace std;

class Base {
public:
    virtual void f( int ) {
        cout << "Base::f(int)" << endl;
    }

    virtual void f( double ) {
        cout << "Base::f(double)" << endl;
    }

    virtual void g( int i = 10 ) {
        cout << i << endl;
    }
};

class Derived: public Base {
    
public:
    using Base::f;

    void f( complex<double> ) {
        cout << "Derived::f(complex)" << endl;
    }

    void g( int i = 20 ) {
        cout << "Derived::g() " << i << endl;
    }
};


int main() {
    Derived d;

    d.f(1.0);
}