繁体   English   中英

为什么类方法不能使用相同的名称调用全局函数?

[英]Why can't a class method call a global function with the same name?

以下代码显示了一个函数调用另一个函数。
两者名称相同,但签名不同。
这按预期工作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM