[ fromfile: namespaces.xml id: namespaces ]
In C and C++ there is one global scope that contains
The names of all global functions and variables
Class and type names which are commonly available to all programs
Classes are one way of grouping names (members) under a common heading (the classname), but sometimes it is desirable to have a higher level grouping of names.
The namespace mechanism provides a way to partition the global scope into individually named sub-scopes. This helps avoid naming conflicts that can arise when developing a program that uses modules with name conflicts.
The syntax for defining a namespace is
namespace namespaceName { decl1, decl2, ...}
Any legal identifier can be used for the optional namespaceName.
Example 20.7. src/namespace/a.h
#include <iostream>
namespace A {
using namespace std;
void f() {
cout << "f from A\n";
}
void g() {
cout << "g from A\n";
}
}
Example 20.7 and Example 20.8 define two separate namespaces in different files, each containing functions with the same name.
Example 20.8. src/namespace/b.h
#include <iostream>
namespace B {
using namespace std;
void f() {
cout << "f from B\n";
}
void g() {
cout << "g from B\n";
}
}
Example 20.9 includes both header files, and uses scope resolution to call functions declared in either file.
Example 20.9. src/namespace/namespace1.cc
#include "a.h"
#include "b.h"
int main() {
A::f();
B::g();
}
Output:
f from A
g from B
The using keyword permits individual members of a namespace to be referenced without scoping.
The syntax can take two forms.
The using directive: using namespace namespaceName - imports the entire namespace into the current scope
The using declaration: using namespaceName::identifier - imports a particular identifier from that namespace
Care must be exercised to make sure that ambiguities are not produced when identifiers are present in more than one included namespace. We show an example of such an ambiguous function call in Example 20.10.
Example 20.10. src/namespace/namespace2.cc
| namespace Aliases | |
|---|---|
To make the names of various namespaces unique, programmers sometimes produce extremely long namespace names. One can easily introduce an alias for a long namespace name with a command such as: namespace xyz = verylongcomplicatednamespacename; |
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |