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

编程入门 行业动态 更新时间:2024-10-26 14:32:06
本文介绍了为什么类方法不能使用相同的名称调用全局函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

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

本文发布于:2023-05-29 21:33:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/353316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   函数   名称   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!