访问重载的基类方法,其名称与派生方法同名 [英] Access overloaded base class method with same name as derived method

查看:58
本文介绍了访问重载的基类方法,其名称与派生方法同名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从基类中调用与派生类中的方法同名的方法.这是一个简化的示例:

I'm attempting to call a method from a base class with the same name as a method in the derived class. Here's a simplified example:

#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)并获取打印基数:1",也就是说,即使它位于基数中,也将自动调用与签名匹配的方法课.

Basically, I'd like to be able to call x.print(1) and get "Printing number from base: 1", that is, automatically call the method which matches the signature, even though it resides in the base class.

在没有using Base::print;的情况下,我得到error: no matching function for call to 'Derived::print(int)',由于名称隐藏,这非常合理.

Without the using Base::print;, I get error: no matching function for call to 'Derived::print(int)', which makes perfect sense due to name hiding.

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

Thus, I added that line, but now the error is error: 'void Base::print(int)' is inaccessible

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

Why is this the case? I use public inheritance, so I would have thought it was readily available?

如示例中所示,手动调用x.Base::print(1);可以很好地工作,但我想更透明地进行操作.然后,我当然可以为派生类中的函数重新实现包装器,但这似乎也不是很优雅.

As demonstrated in the example, it works fine to manually call x.Base::print(1);, but I would like to do it more transparently. Then of course I can re-implement a wrapper to the function in the derived class, but that does not seem very elegant either.

很抱歉,以前的问题已解决此问题,我阅读了其中的很多内容,发现了很多类似的案例,但没有任何帮助.

I apologize if this has been covered in an earlier question, I read a bunch of them and found a lot of similar cases, but nothing that helped me.

推荐答案

using指令的位置决定可见性.只需将其放入公共区域,就可以了:

The placement of the using directive decides about the visibility. Simply place it into the public area and you should be fine:

//...
class Derived : public Base
{

public:
    using Base::print;

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

http://ideone.com/06NNk

这篇关于访问重载的基类方法,其名称与派生方法同名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆