c++ namespace 疑问

sx666777888 2017-12-09 02:03:54
代码如下
namespace.h

namespace my
{
doule fetch = 1.2;
}

main1.cpp

using namespace std;

using namespace my;
double fetch = 1.3;
int main ()
{
cout<<"fetch "<<fetch<<endl;
}


main2.cpp

using namespace std;
int main ()
{
using namespace my;
double fetch = 1.3;
cout<<"fetch "<<fetch<<endl;
}


其中main1编译会报错fetch重定义了,main2确可以编译通过,其实main2我大概明白,局部变量隐藏了名称空间的变量,但是main1为什么不是一样的机制呢?
请大家指教,多谢
...全文
126 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
sx666777888 2017-12-09
  • 打赏
  • 举报
回复
引用 1 楼 xsklld 的回复:
http://en.cppreference.com/w/cpp/language/namespace#Using-directives
引用
From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name.
因此就这两种情况而言,my::fetch 都如同在全局空间声明。所以main1冲突,main2是隐藏。
多谢大师指点,明白了,就是说在main的作用域内,main2中的using namespace my的作用和在外部是一样的效果,但是非main作用域的效果还是不一样的。
xskxzr 2017-12-09
  • 打赏
  • 举报
回复
http://en.cppreference.com/w/cpp/language/namespace#Using-directives
引用
From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name.
因此就这两种情况而言,my::fetch 都如同在全局空间声明。所以main1冲突,main2是隐藏。

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧