C++命名空间

命名空间的作用:避免名字冲突和解决命名空间污染问题

[color=red]命名空间的定义[/color]
[color=blue][b]namespace [/b][i]namespace_name [/i]{
//declarations
}[/color]

例:

/*
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...
}



[color=red]引入某入命名空间的方法[/color]
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();
}

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();
}


一个命名空间是可以分散在多个文件中,在不同文件中的命名空间定义是累积的
[color=red]向一个已存在命名空间引入新的成员[/color]
#include "my.h" //先引入命名空间所声明的头文件
namespace My_lib {
//new members...
}

[color=red]无名命名空间:[/color]将命名空间局限于一个文件中
[color=blue][b]namespace[/b] {
//declarations
}[/color]
在同一个文件中可以直接使用无名命名空间的名字而无需使用作用域操作符或者using声明和指令

[color=red]命名空间的嵌套[/color]:可以在一个命名空间中声明另一个命名空间
例:

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;

[color=red]命名空间别名:[/color]一般是为了方便使用,给较长的命名空间取一个较短的命名空间来使用
取别名的语法:
[color=blue]namespace 源空间名 = 别名;[/color]
能使用别名来访问源命名空间里的成员,但不能为源命名空间引入新的成员

[color=red]命名空间函数重载:[/color]如果从多个命名空间里引入同名而不同参的函数,且它们满足构成重载的条件,则构成重载
例:

//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)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值