如果baseclass有两个同名函数,则找不到baseclass函数

Ben*_*ier 6 c++ inheritance

我有一个基类,它有两个同名的函数,但在2级继承中有不同的签名.

struct A {
    virtual void f(int) { }
    virtual void f(int, int) { };
    virtual void f1(int) { }
};

struct B: public A { };

struct C: public B {
  void f(int, int) { }
  void f1(int) { }
};

int main() {
 C obj;
 obj.f1(0);
 obj.f(0,0);

 obj.f(0);    // (1) cannot be found
 obj.B::f(0); // (2) works

}
Run Code Online (Sandbox Code Playgroud)

我希望我的编译器(gcc-4.3.2)能够找到正确的定义(1),但是我得到了

g++     main.cpp   -o main
main.cpp: In function 'int main()':
main.cpp:20: error: no matching function for call to 'C::f(int)'
main.cpp:10: note: candidates are: virtual void C::f(int, int)
distcc[2200] ERROR: compile main.cpp on localhost failed
make: *** [main] Error 1
Run Code Online (Sandbox Code Playgroud)

(2) 另一方面工作.

(1)一般来说,我需要修理什么才能完成工作?

Lig*_*ica 6

using A::f在C的定义里面

你是名字隐藏的受害者!void C::f(int, int)隐藏void A::f(int),只是因为.


Zan*_*ynx 5

C++名称查找规则具有它,以便如果在一个范围中重新定义名称,则隐藏该名称的所有重载.

但你可以using用来帮忙.像这样:

class A {
    public:
    int f(int x) { cout << "A::f 1\n"; }
    int f(int x, int y) { cout << "A::f 2\n"; }
};

class B : public A {
    public:
    using A::f;
    int f(int x) { cout << "B::f 1\n"; }
};

int main()
{
    B b;

    b.f(27, 34);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

A::f 2
Run Code Online (Sandbox Code Playgroud)