該類名不會與在其他名字空間中聲明的名字
衝突例如
namespace cplusplus_pri mer {
class Node { /* ... */ };
}
namespace DisneyFeatureAnimation {
class Node { /* ... */ };
}
Node *pnode; // 錯誤: Node 在全域域中不可見
// OK: 聲明 nodeObj 的類型為 DisneyFeatureAnimation::Node
DisneyFeatureAnimation::Node nodeObj;
// using 聲明: 使得 node 在全域域中可見
using cplusplus_primer::Node;
Node another; // cplusplus_primer::Node
=============================
// --- primer.h ---
namespace cplusplus_primer {
class List {
// ...
private:
class ListItem {
public:
void check_status();
int action();
// ...
};
};
}
// --- primer.C ---
#include "primer.h"
namespace cplusplus_primer {
// ok: check_status() 在與 List 相同的名字空間中定義
void List::ListItem::check_status() { }
}
// ok: action() 在全域域中定義,
// 在一個包含類 List 定義的名字空間中
// 成員名用名字空間名限定修飾
int cplusplus_primer::List::ListItem::action() { }
=======================
// --- primer.h ---
namespace cplusplus_primer {
class List {
// ...
private:
class ListItem {
public:
int action();
// ...
};
};
const int someVal = 365;
}
// --- primer.C ---
#include "primer.h"
namespace cplusplus_primer {
int List::ListItem::action() {
// ok: cplusplus_primer::someVal
int local = someVal;
// 錯誤: calc() 還沒有聲明
double result = calc( local );
// ...
}
double calc(int) { }
// ...
}