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
384 views
in Technique[技术] by (71.8m points)

overloading - C++: Why member function has priority over global function

Why in the next program the member function foo has priority over the global foo although the global one match the type?

#include <iostream>
using namespace std;

void foo(double val) { cout << "double
";}

class obj {
public:
  void callFoo() { foo(6.4); }
private:
  void foo(int val) {cout << "class member foo
"; }
};

int main() { 
  obj o;
  o.callFoo();
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because the member function named foo could be found at the class scope, and then name lookup will stop, so the global version foo won't be considered for overload resolution, even if the global version is more appropriate here. It is a kind of name hiding.

If you want to call the global version, you could explicitly call it by ::foo(6.4);.

And here is a workaround to bring the global function into overload resolution.

Reference for Unqualified name lookup


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

...