namespace作用是避免程序中的命名冲突,传统的C++程序是只有一个namespace,现在程序越来越复杂,为了防止程序员在合并不同程序时出现函数、类、结构体等命名的重复,所以用到命名空间。
名字空间包含类、函数、常量和模板声明等名字空间成员。例如:
namespace MyUnderstand
{
class info {int number;
string name;
public:
void FristInstance (char *msg);
void SecondInstance(int Num);
};
}
如何将名字空间成员类分离成多个源文件呢?
通过以下例子加以说明:
下面是名为
example.h
的头文件,其中定义了上面的
名字空间MyUnderstand,它包含类
info
的声明:
另外,在一个单独的源文件example
.cpp
中,首先包含头文件
example.h
以便实现类
info
的成员函数
FristInstance ()
和
SecondInstance()
:
//example.cpp
#include "example.h"
void MyUnderstand::info::FristInstance ()
{ /*..*/ }
void MyUnderstand::info::SecondInstance()
{ /*..*/ }
要使用这个名字命名空间的成员,就必须使用这个成员在命名空间的路径,例如用类info就要添加它的全路径名即MyUnderstand::info。这样就能够调用这个命名空间的类。相同的命名空间的函数调用也是如此。
关于using关键字在命名空间的作用解释。
如果不用using关键字当命名空间在.h定义之后在使用命名空间里面的元素时要添加全路径。例如:
//example.h
namespace MyUnderstand
{
class info {int number;
string name;
public:
void FristInstance (char *msg);
void SecondInstance(int Num);
};
}
//example.cpp
#include "example.h"
void MyUnderstand::info::FristInstance ()
{ /*..*/ }
void MyUnderstand::info::SecondInstance()
{ /*..*/ }
使用using声明命名空间之后,在次使用声明时就不用再添加路径;例如:
#include "example.h"
int main()
{
using MyUnderstand::info; //
使用名字空间
info b;
info f;
b.FristInstance ();
f.FristInstance ();
//...
}
using
指令由关键字
“using namespace”
后跟名字空间名构成。在访问名字空间成员时不建议经常使用,其原因是这种方法将所有名字空间成员注入当前的范围,从而增加了潜在的名字冲突。