---
title: "C++命名空间"
author: "longsy"
date: "2009-03-22T01:59:03Z"
tags: []
slug: "c"
draft: false
lastmod: "2009-03-22T13:57:51Z"
id: 353019
url: "https://longsy.iteye.com/blog/353019"
---

命名空间的作用:避免名字冲突和解决命名空间污染问题

<span style="color:red">命名空间的定义</span>
<span style="color:blue">**namespace ***namespace_name *{
   //declarations
}</span>

例:

```c++

/*
file:my.h
author:longsy  
*/
//declare namespace My_lib
namespace My_lib {
   void describe();
}

```

一般命名空间的声明放在头文件中,而实现则放在源文件中
命名空间也是一个作用域,实现命名空间的函数时,要使用作用域操作符(::)

```c++

/*
file:my.c
author:longsy
*/
#include "my.h"
void My_lib::describe()
{
   //do something...
}

```



<span style="color:red">引入某入命名空间的方法</span>
1.using 声明

```c++

/*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 指令

```c++

/*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();
}

```


一个命名空间是可以分散在多个文件中,在不同文件中的命名空间定义是累积的
<span style="color:red">向一个已存在命名空间引入新的成员</span>
#include "my.h" //先引入命名空间所声明的头文件
namespace My_lib {
   //new members...
}

<span style="color:red">无名命名空间:</span>将命名空间局限于一个文件中
<span style="color:blue">**namespace** {
   //declarations
}</span>
在同一个文件中可以直接使用无名命名空间的名字而无需使用作用域操作符或者using声明和指令

<span style="color:red">命名空间的嵌套</span>:可以在一个命名空间中声明另一个命名空间
例:

```c++

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;

<span style="color:red">命名空间别名:</span>一般是为了方便使用,给较长的命名空间取一个较短的命名空间来使用
取别名的语法:
<span style="color:blue">namespace 源空间名 = 别名;</span>
能使用别名来访问源命名空间里的成员,但不能为源命名空间引入新的成员

<span style="color:red">命名空间函数重载:</span>如果从多个命名空间里引入同名而不同参的函数,且它们满足构成重载的条件,则构成重载
例:

```c++

//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)
}

```