Why can#39;t a class method call a global function with the same name?(为什么类方法不能调用同名的全局函数?)
问题描述
以下代码显示一个函数调用另一个函数.
两者名称相同,但签名不同.
这按预期工作.
The following code shows a function call another function.
Both have the same name, but different signatures.
This works as expected.
//declarations
void foo();
void foo(int);
int main(){
foo();
}
//definitions
void foo(){
foo(1);
}
void foo(int){}
我现在要做的唯一区别是将其中一个函数包装成一个结构:
The only difference I will make now, is wrap one of the functions into a structure:
//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) 作为方法,当全局函数存在时.
它没有提到任何关于歧义的事情,只是找不到函数.
I don't understand why it wants to call foo(int) as a method, when the global function exists.
It doesn't mention anything about ambiguity, it just can't find the function.
为什么会发生这种情况,我该如何解决?
Why is this happening, and how can I fix it?
附注:我将旧的 C 代码包装在 C++ 包装器中,并且大多数 C++ 方法都是对全局 C 函数的调用,这些函数隐式地传入包装的结构中.这与上面发生的情况类似(就编译器错误而言).
side note: I'm wrapping old C code in a C++ wrapper, and most of the C++ methods are calls to the global C functions which pass in the wrapped struct implicitly. It's a similar situation to what is happening above (in terms of compiler errors).
推荐答案
成员函数隐藏全局.它在类上下文中找到名称,因此不会在其他上下文中继续搜索.
The member function is hiding the global. It finds the name in the class context, therefore it not continue to search it in other contexts.
你需要这样称呼它:
::foo(1);
另一种解决方案是在函数内部使用前向声明,如下所示:
Another solution is to use forward declaration inside the function, like this:
void Bar::foo()
{
void foo(int);
foo(1);
}
正如 Praetorian 所建议的,这是另一种选择:
As Praetorian suggests, here is another option:
void Bar::foo()
{
using ::foo;
foo(1);
}
这篇关于为什么类方法不能调用同名的全局函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么类方法不能调用同名的全局函数?


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01