当派生类中存在另一个重载时,无法调用基类的方法 [英] Can't call base class's method when another overload present in derived class

查看:57
本文介绍了当派生类中存在另一个重载时,无法调用基类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编译以下代码时,出现编译器错误函数不带0参数".

I get a compiler error "function does not take 0 arguments" when compiling the following code.

class A
{
public:
    int Foo()
    {
        return 1;
    }

protected:
    virtual void Foo(int& n)
    {
        n += 1;
    }
};

class B : public A
{
protected:
    // Override of A
    void Foo(int& n)
    {
        n += 2;
    }
};


int main(int argc, char* argv[])
{

    B b;
    int n = b.Foo();
    return n;
}

看起来编译器坚持要调用重载B :: Foo(int&)而不是A :: Foo().我一定在这里遗漏了一些明显的东西.任何解释编译器行为的指向C ++标准的指针都将受到赞赏.

It looks like the compiler insists on calling overload B::Foo(int&) instead of A::Foo(). I must be missing something obvious here. Any pointers to C++ standard that explain the compiler's behaviour will be appreciated.

我确实意识到"int n =((A)b).Foo();"会让编译器感到高兴,但这对我来说不是一个理想的解决方案.

I do realise that "int n = ((A)b).Foo();" will make the compiler happy but this is not an ideal solution for me.

谢谢.

推荐答案

添加此行:

using A::Foo;

在类 B 中(公开部分),它将起作用.

in class B (public part) and it will work.

在这种情况下, B Foo 隐藏 A 的 Foo .C ++奇怪的行为之一.

In this case Foo from B hides Foo from A. One of the C++ strange behaviors.

这篇关于当派生类中存在另一个重载时,无法调用基类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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