C ++ using namespace operator

namespace MyNamespace { static void foo1() { } } using namespace MyNamespace; class MyClass { void foo2() { ::foo1(); } }; 

The scope resolution operation :: means using the method in the global namespace. Here we can use ::foo1() . That means the foo1() method is in the global namespace, right?

My question is that using namespace ANAMESPACE_NAME means we are importing all elements from the ANAMESPACE_NAME namespace into the global namespace?

+6
source share
4 answers

Section 3.4.3.4 of the C ++ 2003 standard has the answer:

The name preceded by the operator of the unary region :: (5.1) is looked into the global scope in the translation block where it is used. The name must be declared in the global namespace or must be a name, the declaration is visible in the global scope due to the using directive (3.4.3.2).

This paragraph is almost identical in C ++ 11 FDIS, so this probably also occurs in C ++ 11.

+3
source

Not. "using the namespace ANAMESPACE_NAME" means that we import all the elements into the current scope.

You can write something like the following:

 namespace A { int i = 10, j = 20; } int f() { using namespace A; // injects names from A into the global scope. return i * j; // uses i and j from namespace A. } int k = i * j; // Error: undefined variant i and j. 
+5
source

Here we can use :: foo1 (). This means that the foo1 () method is in the global namespace, am I right?

Yes, that's right. This means calling a method named foo1() defined in the global namespace. This is called Qualified Namespace Lookup .

do "using namespace ANAMESPACE_NAME" means that we import all the elements in the ANAMESPACE_NAME namespace into the global namespace?

Yes, it imports all elements from the ANAMESPACE_NAME namespace into the current namespace.
It is called using the directive .
If you want to import only a specific item in the current type, using the declaration .

Format

:

using ANAMESPACE_NAME :: element_name;

+3
source

Source: https://habr.com/ru/post/898915/


All Articles