为什么要有命名空间?
在C/C++中会有大量的函数,变量,类都被保存到全局作用域,很容易导致命名冲突,运行就会报错。
#include <stdio.h>
#include <stdlib.h>
int rand = 10;
int main()
{
printf("%d\n", rand);
return 0;
}
为了解决这个问题,引入命名空间。
命名空间的定义
命名空间的关键字是:namespace,后面跟命名空间的名字,再接一对{}即可,{}里就是命名空间的成员。
#include <stdio.h>
#include <stdlib.h>
namespace code
{
int rand = 10;
}
int main()
{
printf("%d\n", code::rand);
return 0;
}
将rand变量放到code空间去,就不会重定义了。
命名空间还可以定义函数和类。
namespace code
{
int rand = 10;
int Add(int x, int y)
{
return x + y;
}
class A
{
public:
private:
};
}
命名空间还可以嵌套
namespace N1
{
namespace N2
{
}
}
并且同一个工程文件中的多个命名空间还会合并成同一个。
命名空间的使用
- 加命名空间名称及作用域限定符
namespace code
{
int rand = 10;
int Add(int x, int y)
{
return x + y;
}
}
int main()
{
printf("%d\n", code::rand);
return 0;
}
- 使用using将命名空间中某个成员引入
using code::rand;
int main()
{
printf("%d\n", rand);
return 0;
}
- 使用using namespace 命名空间名称 引入
using namespace code;
int main()
{
printf("%d\n", rand);
return 0;
}