Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如果基类有两个同名函数,则找不到基类函数_C++_Inheritance - Fatal编程技术网

C++ 如果基类有两个同名函数,则找不到基类函数

C++ 如果基类有两个同名函数,则找不到基类函数,c++,inheritance,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;

我有一个基类,它有两个同名的函数,但在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

}
我希望我的编译器(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
(2)
在另一方面起作用

我需要修正什么才能使
(1)
在一般情况下起作用?

对“为什么”的简短回答是“因为重载就是这样工作的。”你在C中隐藏了
f(int)
重载。答案越长,越长

您可以通过执行以下操作来取消隐藏它:

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

在C的定义中使用A::f编写


你是隐藏姓名的受害者<代码>空格C::f(int,int)< /> >隐藏代码>空格A::(f)(int)< /> >,因为./p> < p> C++名称查找规则使它在一个范围内重新定义名称时,<强> > <强>隐藏该名称的重载。

但是您可以使用
使用
来帮助。像这样:

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;
}

+1对于写得很好并有完整例子的帖子,你能告诉我们更长的答案吗?@honk:现在不行,我时间不够。但我会寻求一些帮助。时间不长,但这里有一个解释:谢谢@Fred Larson,我应该找到的。@John:永远不要让回答妨碍啤酒时间,对吗<代码>:)
A::f 2