using和名空间namespace

 

using 指令后面跟namespace可以将当前的嵌套层与一个指定的名空间连在一起,以便使该名空间下定义的对象和函数可以被访问。

我们能够直接使用在namespace中定义的变量而不用在前面加任何范围操作符。例如:

           

#include <iostream>
#include <string>
using namespace std;

namespace first
{
int x = 10;
int y = 2;
}
namespace second
{
double x = 3.2;
double y = 2.3;
}

int main{

using namespace first;
cout<<x<<'\n';
cout<<y<<'\n';
cout<<second::x<<'\n';
cout<<second::y<<'\n';
//另一种写法
using first::x;
using second::y;
cout<<x<<'\n';
cout<<y<<'\n';

}

输出:10

        2

        3.2

        2.3

        10

        2.3

 

语句using namespace 只在其被声明的语句块内有效,如果我们想在一段程序中使用一个名空间,而在另一段程序中使用另一个名空间,
则可以像以下代码中那样做:

        int main

                  {

{
using namespace first;
cout<<x<<'\n';
}
{
using namespace second;
cout<<x<<'\n';
}

                 }



posted on 2014-03-07 17:00  guozqzzu  阅读(332)  评论(0编辑  收藏  举报