Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c++ - Why can'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){}

This fails to compile.

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

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?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

You need to call it like this:

::foo(1);

Another solution is to use forward declaration inside the function, like this:

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

As Praetorian suggests, here is another option:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...