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<<' ';
cout<<y<<' ';
cout<<second::x<<' ';
cout<<second::y<<' ';
//另一种写法
using first::x;
using second::y;
cout<<x<<' ';
cout<<y<<' ';

}

输出:10

        2

        3.2

        2.3

        10

        2.3

 

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

        int main

                  {

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

                 }



原文地址:https://www.cnblogs.com/guozqzzu/p/3586797.html