[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;
}