访问重载的基类方法,其名称与派生方法相同

时间:2012-09-13 12:38:42

标签: c++ inheritance

我正在尝试从基类中调用一个方法,该方法的名称与派生类中的方法相同。这是一个简化的例子:

#include <iostream>

using namespace std;

class Base
{
public:
    void print() {
        cout << "Printing from base" << endl;
    }

    void print(int num) {
        cout << "Printing number from base: " << num << endl;
    }
};

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

public:
    void print() {
        cout << "Printing from derived" << endl;
    }
};


int main()
{
    Derived x;

    x.print();
    x.Base::print(1);

    //x.print(1); // Gives a compilation error

    return 0;
}

基本上,我希望能够调用x.print(1)并获得“从base打印数字:1”,即自动调用匹配签名的方法,即使它位于基础中类。

如果没有using Base::print;,我会得到error: no matching function for call to 'Derived::print(int)',因为名称隐藏而非常有意义。

因此,我添加了该行,但现在错误为error: 'void Base::print(int)' is inaccessible

为什么会这样?我使用公共继承,所以我认为它很容易获得?

如示例中所示,它可以正常调用x.Base::print(1);,但我想更透明地完成它。然后我当然可以在派生类中重新实现函数的包装器,但这似乎也不是很优雅。

如果在早期的问题中已经涵盖了这一点,我很抱歉,我读了很多,发现了很多类似的案例,但没有任何帮助我。

2 个答案:

答案 0 :(得分:4)

using指令的放置决定了可见性。只需将它放入公共区域就可以了:

//...
class Derived : public Base
{

public:
    using Base::print;

    void print() {
        cout << "Printing from base" << endl;
    }
};
//...

http://ideone.com/06NNk

答案 1 :(得分:0)

您可以将您的功能设为虚拟。从基类继承的任何未重载的虚函数都将通过派生类调用。

class base 
{
  public:
    virtual void Foo() {}
}

class Derived
{
}

Derived d;
d.foo(); // calls base::foo()
相关问题