C++ 为什么可以';类方法调用具有相同名称的全局函数吗?

C++ 为什么可以';类方法调用具有相同名称的全局函数吗?,c++,function,methods,overloading,function-prototypes,C++,Function,Methods,Overloading,Function Prototypes,下面的代码显示一个函数调用另一个函数。 两者名称相同,但签名不同。 这正如预期的那样有效 //declarations void foo(); void foo(int); int main(){ foo(); } //definitions void foo(){ foo(1); } void foo(int){} 我现在要做的唯一区别是将其中一个函数包装到一个结构中: //declarations struct Bar{ void foo(); }; void fo

下面的代码显示一个函数调用另一个函数。
两者名称相同,但签名不同。
这正如预期的那样有效

//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);
}
另一种解决方案是在函数内部使用转发声明,如下所示:

::foo(1);
void Bar::foo()
{
    void foo(int);
    foo(1);
}
正如裁判官所建议的,这里有另一个选择:

void Bar::foo()
{
    using ::foo;
    foo(1);
}

或者使用::foo添加
Bar::foo中使用
添加
而不使用类名是不合法的。它给出了以下错误:“foo:symbol不能在使用声明的成员中使用”仅在它允许的函数中使用,并且与fw声明类似。VS的哪个版本?在VS2015上编译。@Praetorian在函数中是works(就像转发声明一样),在它没有编译的类中,我将把你的解决方案添加到答案中……是的,不能在类范围内完成。在这种情况下,using声明只能用于将基类成员引入范围。这就是非限定名称查找的工作原理,如果您搜索它,我肯定会有一些重复。