Namespaces qualified with :: in C ++

What does it mean if the namespace in C ++ matches :: ? For example ::testing::Test .

+6
c ++ namespaces
source share
5 answers

:: is the region resolution operator. It always means "look up the global namespace for the character to the right." For example:

 namespace testing { int a = 1; } namespace foo { namespace testing { int a = 2; } int b = ::testing::a; // b has the value 1 int c = testing::a; // c has the value 2 } 
+18
source share

This means that the testing namespace referred to is a name from the global namespace, and not another nested namespace called testing .

Consider the following angular case, and probably an example of poor design:

 namespace foo { struct gizmo{int n_;}; namespace bar { namespace foo { float f_; }; }; }; int main() { using namespace foo::bar; ::foo::gizmo g; g.n_; } 

There are 2 namespaces named foo . One of them is the top level of the "global" namespace, and the other is inside foo::bar . then go to using namespace foo::bar , which means that any unqualified gizmo link will display the value in foo::bar::foo . If we really want this to be in foo , we can use an explicit qualification for this:

::foo::gizmo

+5
source share

If :: used on the left side, it means a global scope.

If you need an analogy with the file system, testing::Test will be a kind of relative path (relative to the KΓΆnig lookup ), while ::testing::Test will be the absolute path. I hope this analogy clarifies the situation and does not spoil your mind :-).

+3
source share

I, if you precede a variable name with ::, it resolves the variable to a global scope. Thus, you can have both local testing of variables and testing of global variables and distinguish between them.

 #include <iostream> using namespace std; int testing = 37; int main() { int testing = 42; cout << ::testing << ' ' << testing << endl; } 

The output will be 37 42

+3
source share

This calls something called qualified name lookup:

$ 3.4.3 / 1 - "The name of a class or namespace element can be referenced after the scope statement (scope) (5.1) applied to a nested qualifier that assigns its class or namespace. During a search for a name preceding the statement scope permissions, names of objects, functions and enumerators are ignored. If the name found is not a class name (section 9) or namespace-name (7.3.1), the program is inactive, it is formed. "

0
source share

All Articles