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

前端 未结 6 776
青春惊慌失措
青春惊慌失措 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:46

    Consider what would happen if a global function declared somewhere in your code base (possibly several #include statements away) would trump an class obj member function declared right there in the class itself...

    It would mean that, if you want to play it safe, you would have to fully qualify every single call to a member function...

    this->foo();
    

    ...instead of having to qualify the less likely case of actually referring to the global function.

    ::foo();
    

    This is called the "concept of least surprise".

提交回复
热议问题