using namespace std;
这句话大家已经写过不知道多少遍了,但有人自己创建过一个名字空间吗?
Namespace的定义:
- namespace的定义必须是在global scope中,或在别的namespace中
- 定义的最后不用跟分号
- 一个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;
}
浙公网安备 33010602011771号