您的位置:首页 > 其它

第十六周 阅读程序一(3)

2015-06-17 14:26 134 查看
问题及代码:

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


运行结果:



学习心得:

请回答:

(a)(d)处:为什么可以省去CounterNameSpace::?

因为using CounterNameSpace::upperbound;已经明确了upperbound的命名空间。

(b)(c)处:是否可以省去CounterNameSpace::?

不可以省去,省去就会发生命名冲突。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: