using 关键字的作用是使一个名字空间变得可见。比如容易想到,如果在程序中需要大量的使用某个名字空间中的成员,而每次又不得不使用作用域解析运算符,这样将显得冗长且繁琐。using 正是为了解决这个问题而来的。using 语句有两种通用形式:using namespace name;
using name::member; 在第一种形式中,name 是需要使用的名字空间。所有定义在该名字空间中的成员将变得可见,并且在使用这些成员时不需要加上作用域解析运算符。比如我们常用的 using namespace std; 。
在第二种形式中,我们指定了名字空间 name 中一个特定的成员是可见的。
示例程序:
[C++] 纯文本查看 复制代码 // namespace.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//声明自己的名字空间
namespace CounterNameSpace {
int upperbound;
int lowerbound;
class counter {
int count;
public:
counter(int n)
{
if (n <= upperbound)
count = n;
else
count = upperbound;
}
void reset(int n)
{
if (n <= upperbound)
count = n;
}
int run()
{
if (count > lowerbound)
return count--;
else
return lowerbound;
}
};
}
int _tmain(int argc, _TCHAR* argv[])
{
//仅使用 CounterNameSpace 中的变量 upperbound
using CounterNameSpace::upperbound;
//现在不需要指定 upperbound 的所属作用域了
upperbound = 100;
//对于 CounterNameSpace 中的其它成员,仍然需要使用限定符
CounterNameSpace::lowerbound = 0;
CounterNameSpace::counter ob1(10);
int i;
do {
i = ob1.run();
cout << i << " ";
}while ( i > CounterNameSpace::lowerbound);
cout << endl;
//现在可以使用整个 CounterNameSpace 中的成员了
using namespace CounterNameSpace;
counter ob2(20);
do {
i = ob2.run();
cout << i << " ";
} while ( i > CounterNameSpace::lowerbound);
cout << endl;
ob2.reset(100);
CounterNameSpace::lowerbound = 90;
do {
i = ob2.run();
cout << i << " ";
}while (i > CounterNameSpace::lowerbound);
return 0;
} |