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

前端 未结 6 775
青春惊慌失措
青春惊慌失措 2020-12-17 21:14

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

#include 
using name         


        
6条回答
  •  误落风尘
    2020-12-17 21:37

    You could think of it as increasing "specialisation" as you move from the global namespace through any nested namespaces around your class, nested classes etc. down to the member functions involved. If you say "foo" in this inner context, a more "specialised" foo can be expected to be more relevant to the caller. Further, if the global one was used preferentially, then someone adding symbols to a less "specialised" scope could break a class that defined a same-named symbol, undoing a lot of the benefits of namespaces and identifier scoping. The basic idea is that your class has a lot of freedom to use meaningful but concise identifiers - which may well be used by other code in your application - but it's only when a meaning for that identifier isn't available in the most local scope that it starts looking further and further afield.

提交回复
热议问题