What is the meaning of prepended double colon “::”?

前端 未结 9 2067
鱼传尺愫
鱼传尺愫 2020-11-22 15:54

I found this line of a code in a class which I have to modify:

::Configuration * tmpCo = m_configurationDB;//pointer to current db

and I do

相关标签:
9条回答
  • 2020-11-22 16:26

    its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
    For example;

    int x;
    void f2()
    {
       int x = 1; // hide global x
       ::x = 2; // assign to global x
       x = 2; // assign to local x
       // ...
    }
    
    0 讨论(0)
  • 2020-11-22 16:31

    :: is a operator of defining the namespace.

    For example, if you want to use cout without mentioning using namespace std; in your code you write this:

    std::cout << "test";
    

    When no namespace is mentioned, that it is said that class belongs to global namespace.

    0 讨论(0)
  • 2020-11-22 16:37

    (This answer is mostly for googlers, because OP has solved his problem already.) The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.

    The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?

    Use case - namespace clash

    When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in @Wyatt Anderson's answer, plese see his example.

    Use case - emphasise non-member function

    When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:

    class A {
       void DoSomething() {
          m_counter=0;
          ...
          Twist(data); 
          ...
          Bend(data);
          ...
          if(m_counter>0) exit(0);
       }
       int m_couner;
       ...
    }
    

    But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.

    So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.

    0 讨论(0)
提交回复
热议问题