我是一只小小小小鸟

导航

 
using namespace std;
这句话大家已经写过不知道多少遍了,但有人自己创建过一个名字空间吗?

Namespace的定义:

  1. namespace的定义必须是在global scope中,或在别的namespace中
  2. 定义的最后不用跟分号
  3. 一个namespace定义可能会出现在很多头文件中。

下面给出一个最简单的namespace的定义和使用

//myNamespace.h
#include <string>
namespace myNamespace
{
class htx
{
public:
htx();
htx(std::
string);
std::
string getName();
private:
std::
string name;
};
}

//myNamespace.cpp

#include
"myNamespace.h"
myNamespace::htx::htx()
{
}
myNamespace::htx::htx(std::
string a)
{
name
= a;
}
std::
string myNamespace::htx::getName()
{
return name;
}
//test.cpp
#include <iostream>
#include
"test.h"
#include
"myNamespace.h"
using namespace std;
int i;
int main()
{
myNamespace::htx htx(
"htx");
cout
<< htx.getName() << endl;
}

名字空间是能嵌套的

namespace U
{
namespace F
{
int k;
}
}
int main()
{
U::F::k
= 1;
}

posted on 2011-03-28 16:33  cloudygoose  阅读(368)  评论(0)    收藏  举报