以下代码显示了一个函数调用另一个函数。
两者具有相同的名称,但签名不同。
这按预期工作。
//declarations
void foo();
void foo(int);
int main(){
foo();
}
//definitions
void foo(){
foo(1);
}
void foo(int){}
我现在要做的唯一区别是将其中一个函数包装到一个结构中:
//declarations
struct Bar{
void foo();
};
void foo(int);
int main(){
Bar bar;
bar.foo();
}
//definitions
void Bar::foo(){
foo(1);
}
void foo(int){}
编译失败。
In member function ‘void Bar::foo()’:
error: no matching function for call to ‘Bar::foo(int)’
foo(1);
^
note: candidate: void Bar::foo()
void Bar::foo(){
^
note: candidate expects 0 arguments, 1 provided
我不明白为什么它要调用 foo(int) 作为方法,当全局函数存在时。
它没有提到任何关于歧义的事情,它只是找不到功能。
为什么会发生这种情况,我该如何解决?
旁注:我将旧的 C 代码包装在 C++ 包装器中,并且大多数 C++ 方法都是对隐式传入包装结构的全局 C 函数的调用。这与上面发生的情况类似(就编译器错误而言)。
最佳答案
成员函数隐藏了全局。它在类上下文中找到名称,因此它不会继续在其他上下文中搜索它。
你需要这样调用它:
::foo(1);
另一种解决方案是在函数内部使用前向声明,如下所示:
void Bar::foo()
{
void foo(int);
foo(1);
}
正如 Praetorian 所建议的,这是另一种选择:
void Bar::foo()
{
using ::foo;
foo(1);
}
关于c++ - 为什么类方法不能调用同名的全局函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33292215/