C++命名空间

C++引入命名空间,作为附加信息来区分不同库中相同名称的函数,类,变量等,使用了命名空间即定义了上下问,本质上命名空间就是定义了一个范围。

定义命名空间:

命令空间的定义使用关键字namespace,后面跟命名空间的名称,如下所示:

namespace namespace_name
{
    //代码声明
}

为了调用带有命名空间的函数或变量,需要在前面加上命名空间的名称,如下:

name::code;

 

采用实例来看看命名空间如何为变量或函数等实体定义范围

/***
namespace.cpp
***/
#include<iostream>
using namespace std;

namespace first_space
{
    void func()
    {
        cout << "Inside first_space " << endl;
    }
}
namespace second_space 
{
    void func()
    {
        cout << "Inside second_space " << endl;
    }
}

int main()
{
    first_space::func();
    second_space::func();
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190814$ g++ namespace.cpp -o namespace

exbot@ubuntu:~/wangqinghe/C++/20190814$ ./namespace

Inside first_space

Inside second_space

 

using指令

可以使用using namespace 指令,这样在使用命令空间时就可以不用在前面的加上命令空间的名称。这个指令会告诉编译器,后续的代码将使用指定命名空间中的名称。

/***
using.cpp
***/
#include<iostream>
using namespace std;

namespace first_space
{
    void func()
    {
        cout << "Inside first_space " << endl;
    }
}
namespace second_space 
{
    void func()
    {
        cout << "Inside second_space " << endl;
    }
}

using namespace first_space;
int main()
{
    func();
    return 0;

}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190814$ g++ using.cpp -o using

exbot@ubuntu:~/wangqinghe/C++/20190814$ ./using

Inside first_spaced

 

using指令也可以用来指定命令空间中的 特定项目,例如,如果只打算使用std命令空间的cout部分,可以使用以下语句:

using std::cout;

在随后的代码中,在使用cout时就可以不用加上命名空间名称作为前缀了,但是str命令空间中其他项目仍然需要加上命令空间作为前缀:

/***
std.cpp
***/
#include<iostream>
using std::cout;

int main()
{
    cout << "std::endl is used with std" << std::endl;
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190815$ g++ std.cpp -o std

exbot@ubuntu:~/wangqinghe/C++/20190815$ ./std

std::endl is used with std

 

using指令引入的名称遵循正常的范围规则,名称从使用using指令开始可见的,直到该范围结束。此时在范围之外定义的同名实体是隐藏的。

 

不连续的命名空间

命名空间可以定义在几个不同的部分中,因此命名空间是由几个单独定义的部分组成的。一个命名空间的各个组成部分可以分散在多个文件中,所以如果命名空间中的某个组成部分需要请求定义在另一个文件中的名称,仍然需要声明该名称。下面的命名空间定义可以是定义一个新的命名空间,也可以是为已有的命名空间增加新的元素。

namespace namespace_name
{
    //代码声明
}

嵌套的命名空间

命名空间可以嵌套,可以在一个命名空间中定义另一个命名空间:

namespace namespace_name1
{
    //代码声明
    namespace namespace_name1
{
            //代码声明
}
}

实例:

/***
name.cpp
***/
#include<iostream>
using namespace std;

namespace first_space
{
    void func()
    {
        cout << "Inside first_space" << endl;
    }
    namespace second_space
    {
        void func()
        {
            cout << "Inside second_space" << endl;
        }
    }
}

using namespace first_space::second_space;

int main()
{
    func();
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190815$ ./name

Inside second_space

posted @ 2019-08-15 16:59  王清河  阅读(586)  评论(0编辑  收藏  举报