问题及代码;
#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 main()
{
using CounterNameSpace::upperbound;
upperbound = 100; //(a)
CounterNameSpace::lowerbound = 0; //(b)
CounterNameSpace::counter ob1(10);
int i;
do
{
i = ob1.run();
cout << i<<" ";
}
while( i > CounterNameSpace::lowerbound);
cout << endl;
using namespace CounterNameSpace;
counter ob2(20);
do
{
i = ob2.run();
cout << i<<" ";
}
while( i > CounterNameSpace::lowerbound); //(c)
cout << endl;
ob2.reset(100);
lowerbound = 90; //(d)
do
{
i = ob2.run();
cout << i <<" ";
}
while( i > lowerbound);
return 0;
}
运行结果:
学习总结: (b)(c)处的不能省去CounterNameSpace::不能省去,这两处是在调用该命名空间的函数,如果省去的话会产生名字冲突。