当派生类中存在另一个重载时,无法调用基类的方法

bdr*_*tan 5 c++

编译以下代码时出现编译器错误“函数不接受 0 个参数”。

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢。

agn*_*nor 4

添加这一行:

using A::Foo;
Run Code Online (Sandbox Code Playgroud)

在课堂上B(公共部分)它会起作用。

在这种情况下Foo, fromB 隐藏 FooA。C++ 奇怪的行为之一。