What is name lookup mechanism?

后端 未结 3 598
一向
一向 2021-02-09 00:26

I\'d like to know what C++ name lookup mechanism is.

3条回答
  •  误落风尘
    2021-02-09 00:56

    I don't know whether you ask for an analogy to describe what name lookup is. But I will give a possible answer to the above question. Before looking deeply into name lookup mechanism, let's mapping two concepts for fun and use.

    1. scope -> directory
    2. object -> file

    I don't want to explain the reason for this analogy. In the following literal way of thinking, replace scope by directory every time scope is encountered. So does object by file.

    #include 
    
    using namespace std;
    
    namespace Newton{
        double distance, time;
        double velocity(const double &, const double &);
    }
    namespace Einstein{
        double distance, time;
        double velocity(const double &, const double &);
    }
    
    int main()
    {
        using namespace Newton;
        double s(10), t(10);
        velocity(s,t);
        return 0;
    }
    
    double Newton::velocity(const double & s, const double & t){
        distance = s;
        time = t;
        cout << "Calculation by Newton" << endl;
        return distance / time;
    }
    
    double Einstein::velocity(const double & s, const double & t){
        distance = s;
        time = t;
        cout << "Calculation by Einstein" << endl;
        return distance / time;
    }
    

    in this code, what is the implementation of velocity? We meet velocity funciton in the socpe of main(). If you name it like a path name in the file explorer, velocity is actually /Main/velocity. Of course, if you check object names under /Main/, there are still two double objects, s and t, and one namespace object, Newton. If you list the names of objects under /Main/double/, I think the built-in function does not matches an object named velocity, which means, for example, there is no such object -- /Built-in Types/double/velocity. If you list the names of objects again under /Main/Newton/, the actual directory is search is /Newton/ because it is declared there. Then, list the object names under /Newton/, we find two double objects, distance and time, and one function named velocity. Yes, we find a candidate function for /Main/velocity.

    I can only give an analogy of name lookup in c++. There is more to add to conclude a mechanism.

提交回复
热议问题