- namespace space_name {
- ... //可以出現在全局作用域的任意聲明,包括可以是其他命名空間
- }
2.從命名空間外部使用命名空間成員。如下A和B兩種方式,其它簡化訪問的方法稍後討論。
- namespace cpp_primer {
- class Query{
- ...
- };
- }
- cpp_primer::Query q = cpp_primer::Query("hello"); //A
- using cpp_primer::Query;
- Query q = Query("hello"); //B
4.接口和實現分離。可以使用頭文件和實現文件來組織命名空間。
5.定義命名空間成員。在命名空間內部定義和外部定義兩種方式形如:
- //內部定義方式
- namespace cpp_primer {
- class SalesItem {
- // ...
- };
- std::istream&
- operator>>(std::istream& in, SalesItem& s) {
- // ...
- }
- }
- //外部定義方式
- cpp_primer::SalesItem
- cpp_primer::operator+(const SalesItem& lhs, const SalesItem& rhs) {
- SalesItem ret(lhs);
- // ...
- }
6.不能在不相關的命名空間中定義成員。例如函數cpp_primer::operator+()可以在cpp_primer命名空間中定義,也可以使用限定形式在全局作用域中定義。但是不能定義到另一個無關的命名空間內部。
7.關於全局命名空間。如果沒有限定,定義在全局作用域的名字就是定義在全局空間中的。全局命名空間沒有名字,所以使用::member_name來引用全局命名空間的成員。
8.嵌套命名空間。是一種層次結構,例如:
- namespace A {
- namespace B {
- class Something {
- // ...
- };
- }
- }
9.未命名的命名空間。命名空間可以是未命名的,未命名的命名空間在定義時沒有給定名字。
- namespace {
- int i;
- }
10.命名空間的別名。可以用命名空間別名將較短的同義詞與命名空間名字相關聯。例如:
- namespace an_example_namespace {
- // ...
- }
- namespace aens = an_example_namespace;
- using namespace std;
參考:
C++ Primer中文版(第四版)