The namespace keyword allows you to partition the global namespace by creating a declarative region. In essence, a namespace defines a scope. The general form of namespace is shown here:

 namespace name {      // declarations }

In addition, you can have unnamed namespaces as shown here:

 namespace {      // declarations }

Unnamed namespaces allow you to establish unique identifiers that are known only within the scope of a single file.

Here is an example of a namespace:

namespace MyNameSpace {   int i, k;   void myfunc(int j) { cout << j; } }

Here, i, k, and myfunc( ) are part of the scope defined by the MyNameSpace namespace.

Since a namespace defines a scope, you need to use the scope resolution operator to refer to objects defined within one. For example, to assign the value 10 to i, you must use this statement:

MyNameSpace::i = 10;

If the members of a namespace will be frequently used, the using directive can simplify their access. The using statement has these two general forms:

 using namespace name; using name::member; 

In the first form, name specifies the name of the namespace you want to access. All of the members defined within the specified namespace can be used without qualification. In the second form, only a specific member of the namespace is made visible. For example, assuming MyNameSpace as shown above, the following using statements and assignments are valid:

using MyNameSpace::k; // only k is made visible k = 10; // OK because k is visible using namespace MyNameSpace;  // all members of MyNameSpace are visible i = 10;  // OK because all members of MyNameSpace are now visible

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: