[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() //在名字空间中,函数可以直接使用空间中定义的变量lowerbound
{
if (count > lowerbound)
return count--;
else
return lowerbound;
}
};
}
int _tmain(int argc, _TCHAR* argv[])
{
CounterNameSpace::upperbound = 100; //名字空间外的代码访问名字空间内的成员时需要在成员名前加上作用域解析运算符(::)
CounterNameSpace::lowerbound = 0;
CounterNameSpace::counter ob1(10);
int i;
do {
i = ob1.run(); //声明了counter类型对象后,就无需再次限定对象成员的作用域(这里直接调用 ob1.run()),因为编译器已经知道了对象所在的作用域
cout << i << " ";
}while ( i > CounterNameSpace::lowerbound);
cout << endl;
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;
}