命名空间的作用:避免名字冲突和解决命名空间污染问题
命名空间的定义
namespace namespace_name {
//declarations
}
例:
- /*
- file:my.h
- author:longsy
- */
- //declare namespace My_lib
- namespace My_lib {
- void describe();
- }
/* file:my.h author:longsy */ //declare namespace My_lib namespace My_lib { void describe(); }
一般命名空间的声明放在头文件中,而实现则放在源文件中
命名空间也是一个作用域,实现命名空间的函数时,要使用作用域操作符(::)
- /*
- file:my.c
- author:longsy
- */
- #include "my.h"
- void My_lib::describe()
- {
- //do something...
- }
/* file:my.c author:longsy */ #include "my.h" void My_lib::describe() { //do something... }
引入某入命名空间的方法
1.using 声明
- /*I have defined my namespace in the file named "my.h"
- and I also have implemented the namespace in the "my.c"
- */
- /*
- file:test1.c
- author:longsy
- */
- #include "my.h"
- //using声明,引入describe函数,只需要引入名字,不需要带括号和参数
- using My_lib::describe; //也可以将该语句放入函数中
- void test1()
- {
- describe(); //My_lib::describe();
- }
/*I have defined my namespace in the file named "my.h" and I also have implemented the namespace in the "my.c" */ /* file:test1.c author:longsy */ #include "my.h" //using声明,引入describe函数,只需要引入名字,不需要带括号和参数 using My_lib::describe; //也可以将该语句放入函数中 void test1() { describe(); //My_lib::describe(); }
2.using 指令
- /*I have defined my namespace in the file named "my.h"
- and I also implemente the namespace in the "my.c"
- */
- /*
- file:test2.c
- author:longsy
- */
- #include "my.h"
- //using指令,引入My_lib空间中的所有名字
- using namespace My_lib; //也可以将该语句放入函数中
- void test2()
- {
- describe(); //My_lib::describe();
- }
/*I have defined my namespace in the file named "my.h" and I also implemente the namespace in the "my.c" */ /* file:test2.c author:longsy */ #include "my.h" //using指令,引入My_lib空间中的所有名字 using namespace My_lib; //也可以将该语句放入函数中 void test2() { describe(); //My_lib::describe(); }
一个命名空间是可以分散在多个文件中,在不同文件中的命名空间定义是累积的
向一个已存在命名空间引入新的成员
#include "my.h" //先引入命名空间所声明的头文件
namespace My_lib {
//new members...
}
无名命名空间:将命名空间局限于一个文件中
namespace {
//declarations
}
在同一个文件中可以直接使用无名命名空间的名字而无需使用作用域操作符或者using声明和指令
命名空间的嵌套:可以在一个命名空间中声明另一个命名空间
例:
- namespace A{
- int i; //A::i
- int j;
- namespace B{
- int i;
- int k=j;//A::j
- } //end of B scope
- int h = i; //A::i
- } // end of A scope
namespace A{ int i; //A::i int j; namespace B{ int i; int k=j;//A::j } //end of B scope int h = i; //A::i } // end of A scope
引用嵌套里的名字时,使用多层作用域操作符
using A::B::k;
或 using namespace A::B;
命名空间别名:一般是为了方便使用,给较长的命名空间取一个较短的命名空间来使用
取别名的语法:
namespace 源空间名 = 别名;
能使用别名来访问源命名空间里的成员,但不能为源命名空间引入新的成员
命名空间函数重载:如果从多个命名空间里引入同名而不同参的函数,且它们满足构成重载的条件,则构成重载
例:
- //a.h
- namespace A{
- void f(char) {//...}
- }
- //b.h
- namespace B{
- void f(int) {//...}
- }
- //test.c
- #include "a.h"
- #include "b.h"
- void test()
- {
- using A::f;
- using B::f;
- f('a');//A::f(char)
- f(10);//B::f(int)
- }