In depth analysis of C++ programming scope resolution operator role and use

  • 2020-05-07 20:10:38
  • OfStack

Scope resolution operator :: used to identify and eliminate identifiers used in different scopes.
grammar


:: identifier class-name :: identifier namespace :: identifier enum class :: identifier enum struct :: identifier

note
identifier can be a variable, function, or enumeration value.
has namespaces and classes
the following example shows how the scope resolution operator is used with namespaces and class 1:


namespace NamespaceA{
  int x;
  class ClassA {
  public:
    int x;
  };
}

int main() {

  // A namespace name used to disambiguate
  NamespaceA::x = 1;

  // A class name used to disambiguate
  NamespaceA::ClassA a1;
  a1.x = 2;

}

A scope resolution operator without a scope qualifier represents a global namespace.


namespace NamespaceA{
  int x;
}

int x; 

int main() {
  int x;

  // the x in main()
  x = 0; 
  // The x in the global namespace
  ::x = 1; 

  // The x in the A namespace
  NamespaceA::x = 2; 
}

You can use the scope resolution operator to identify members of a namespace, as well as to identify the namespace of a namespace specified by using. In the following example, you can qualify ClassB with NamespaceC (although ClassB is declared in NamespaceB) because NamespaceB is specified in NamespaceC by using directive.


namespace NamespaceB {
  class ClassB {
  public:
    int x;
  };
}

namespace NamespaceC{
  using namespace B;

}
int main() {
  NamespaceB::ClassB c_b;
  NamespaceC::ClassB c_c;

  c_b.x = 3;
  c_c.x = 4;
}

You can use a chain of range resolution operators. In the following example, NamespaceD::NamespaceD1 identifies the nested namespace NamespaceD1, and NamespaceE::ClassE::ClassE1 identifies the nested class ClassE1.


namespace NamespaceD{
  namespace NamespaceD1{
    int x;
  }
}

namespace NamespaceE{

  class ClassE{
  public:
    class ClassE1{
    public:
      int x;
    };
  };
}

int main() {
  NamespaceD:: NamespaceD1::x = 6;
  NamespaceE::ClassE::ClassE1 e1;
  e1.x = 7 ;
}

has static members
must use the scope resolution operator to invoke the static member of the class.


class ClassG {
public:
  static int get_x() { return x;}
  static int x;
};

int ClassG::x = 6;

int main() {

  int gx1 = ClassG::x;
  int gx2 = ClassG::get_x(); 
}

has a scoped enumeration
The
scope-discriminating parsing operator can also be used with the scope-discriminating enumeration, as shown in the following example:


enum class EnumA{
  First,
  Second,
  Third
};

int main() {

  EnumA enum_value = EnumA::First;
}


Related articles: