分类: C/C++
2011-03-23 18:03:22
http://hi.baidu.com/wangjianzhong1981/blog/item/3de6e30eefc9e6c37acbe16d.html
In C++, one can use an unnamed namespace to declare an entity local to a file. An unnamed namespace definition begins with the keyword namespace. Because the namespace is unnamed, no name follows the namespace keyword. Following the namespace keyword is a block of declarations delimited by curly braces.
For example:
// ----- SortLib.C -----
namespace {
void swap( double *d1, double *d2 ) { /* ... */ }
}
// definitions of the sort functions as above
The function swap() is visible only within the file SortLib.C. If another file contains an unnamed namespace with the definition of a function swap(), the definition introduces a different function. The fact that there exist two definitions for the functions swap() is not an error, because the functions are different functions. Unnamed namespaces are not like other namespaces; the definition of an unnamed namespace is local to a particular file and never spans multiple text files.
The name swap() can be referred to in its short form in the file SortLib.C, following the definition of the unnamed namespace. It is not necessary to use the scope operator to refer to members of unnamed namespaces.
void quickSort( double *d1, double *d2 ) {
// ...
double* elem = d1;
// ...
// refers to unnamed namespace member swap()
swap( d1, elem );
// ...
}
The members of an unnamed namespace are program entities. The function swap() can therefore be called throughout the duration of the program. However, the names of the members of an unnamed namespace are visible only within a specific file and are invisible to the other files that make up the program.