概念
命名空间是用来组织和重用代码的编译单元。多人协同开发时,解决重名现象,通过命名空间来避免冲突。定义: namespace命名空间标识符
#include <iostream>
#include <string>
using namespace std;
namespace AA
{
int a = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
int main()
{
return 0;
}
注意事项:
1.必须满足标识符的命名规则和命名规范
在类内定义变量和函数
2.可以在全局,也可以在局部(命名空间接受嵌套定义),但不能在函数内和类中定义。
定义在函数中,例如BB报错
#include <iostream>
#include <string>
using namespace std;
namespace AA
{
int a = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
int main()
{
namespace BB
{
int b = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
return 0;
}
定义在全局括号内也会报错
#include <iostream>
#include <string>
using namespace std;
namespace AA
{
int a = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
{
namespace BB
{
int b = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
};
int main()
{
return 0;
}
可以在类的下面再对类进行定义(命名空间的嵌套定义),就像大箱子里还有小箱子,若要进行调用如下:
#include <iostream>
#include <string>
using namespace std;
namespace AA
{
int a = 10;
void fun()
{
cout << "welcome !" << endl;
}
namespace BB
{
int b = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
}
int main()
{
AA::BB::b = 11; //AA类下嵌套BB类,调用b
cout << AA::BB::b << endl;
return 0;
}
3.命名空间的花括号是作用域
4.如果两个命名空间名同名,就会合并两个命名空间。
#include <iostream>
#include <string>
using namespace std;
namespace AA
{
int a = 10;
void fun()
{
cout << "welcome !" << endl;
}
namespace BB
{
int b = 10;
void fun()
{
cout << "welcome !" << endl;
}
}
}
namespace AA
{
int d = 30;
}
int main()
{
cout << AA::d << endl;
return 0;
}
命名空间的访问
1.using声明: using命名空间名称::空间成员名称
using AA::a;
cout<< a << endl;
2.using指示:using namespace命名空间名
using namespace AA::BB;
fun();
3.命名空间名称::成员名称,直接访问空间下的某一个成员
AA::BB::b = 11;
cout << AA::BB::b << endl;
命名空间取别名:
namespace 别名=命名空间名(注意此时不能再重新定义类A)
namespace A = AA;