- 使用关键字namespace定义命名空间,用{}确定命名空间的限制域
#include<iostream>
#include<Windows.h>
using namespace std;
//命名空间SWK
namespace SWK
{
void test(int a, int b)
{
cout << a + b;
}
}
//命名空间DK
namespace DK
{
int test(int a, int b)
{
return a + b;
}
}
int main()
{
SWK::test(2, 3); //调用SWk中的test
cout << endl;
cout << DK::test(2, 3); //掉用DK中的test
return 0;
}
有时候也会遇到命名冲突的情况,此时有两种方法区分名称空间
- 一种是空域,例如
::test(2,3); //使用的是全局的命名空间 test(2,3); //使用的局部的命名空间
空域使用的是全局的名称空间,即最上面声明的using namespace
另一种是就是限制命名空间了,即老老实实写上 “命名空间名称+::”,例如
SWK::test(2,3); DK::test(2,3);
实例,依然使用SWK和DK两个命名空间,注意注释部分
#include<iostream> #include<Windows.h> using namespace std; using namespace SWK; //全局命名空间 //命名空间SWK namespace SWK { void test(int a, int b) { cout << a + b; } } //命名空间DK namespace DK { int test(int a, int b) { return a + b; } } using namespace DK; //局部命名空间 int main() { ::test(2, 3); //调用SWK中的test cout <<test(2,3); //调用DK中的test cout << DK::test(2, 3); return 0; }
- 一种是空域,例如