微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

派生类隐藏基类同名方法

如何解决派生类隐藏基类同名方法

我正在阅读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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。