1. 基本形式
x.h
namespace Name
{
class C
{
public:
void F();
private:
...
};
}
#include "x.h"
namespace Name
{
void C::F()
{
//...
return;
}
}
2. 名字隐藏
命名空间内的类、函数、变量、类型别名会隐藏外部空间的同名类、函数、变量、类型别名;
3. 宏定义不受命名空间束缚
宏定义一旦产生,无论命名空间内外,于此后代码一律可见。
同一宏可以多次定义。
namespace Device
{
#define HEART_BEAT "method"
}
namespace Client
{
std::string sMsg1 = HEART_BEAT;
#define HEART_BEAT "HeartBeat"
std::string sMsg2 = HEART_BEAT;
}
std::string sMsg3 = HEART_BEAT;
int main()
{
printf("sMsg1=%s\nsMsg2=%s\nsMsg3=%s\n", Client::sMsg1.c_str(), Client::sMsg2.c_str(), sMsg3.c_str());
std::cin.get();
return 0;
}
结果
4. 命名空间可以不连续
namespace nsp
{
//相关声明和定义
}
如果之前没有名为nsp的命名空间,则上述代码创建一个新的命名空间;否则,上述代码打开已经存在的命名空间并为其添加新成员。