9

这是一个带有简单代码粘贴的 ideone 链接:http: //ideone.com/BBcK3B

基类有一个无参数函数,而派生类有一个带参数的函数。一切都是公开的。

为什么从 B 的实例调用时编译器找不到 A::foo()?

编码:

#include <iostream>
using namespace std;

class A
{
public:
    virtual void foo()
    {
        cout << "A::foo" << endl;
    }
};

class B : public A
{
public:
    void foo(int param)
    {
        cout << "B::foo " << param << endl;
    }
};

int main()
{
    B b;
    b.foo();
}

编译器错误:

prog.cpp: In function ‘int main()’:
prog.cpp:25:11: error: no matching function for call to ‘B::foo()’
     b.foo();
           ^
prog.cpp:25:11: note: candidate is:
prog.cpp:16:10: note: void B::foo(int)
     void foo(int param)
          ^
prog.cpp:16:10: note:   candidate expects 1 argument, 0 provided
4

1 回答 1

15

这是标准的 C++ 行为:无论参数和限定符如何,基类方法都被同名的派生类方法隐藏。如果你想避免这种情况,你必须明确地使基类方法可用:

class B : public A
{
  public:
    void foo(int param)  // hides A::foo()
    {
        cout << "B::foo " << param << endl;
    }
    using A::foo;        // makes A::foo() visible again
};
于 2013-08-07T10:28:31.110 回答