// main.cpp
const double MAX = 3.5;
namespace ns
{
const int MAX = 3;
}
int main()
{
}
这会导致重定义错误吗?
我指的是 this MSDN page ,它在备注部分说这是一个错误。
更新:我想我在复制代码时可能会错过一个重要的声明。
using ns::MAX;
最佳答案
否 - 我不明白该代码将如何导致重定义错误。
事实上,您可以 compile it and see for yourself .
编辑:现在您已经提供了指向您提到的 MSDN 页面的链接...
该 MSDN 页面讨论的是 using
directive 上下文中的名称冲突:
If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is an error to have a namespace variable with the same name as a global variable.
Here's an example隐藏由 using
指令引入范围的命名空间变量的局部变量:
namespace ns
{
const int MAX = 3;
}
using namespace ns;
int main()
{
int MAX = 4; // local
int test = MAX; // test is 4, because the local variable is used
// as the namespace variable is hidden
}
using
指令的包含将所有在 ns
命名空间内声明的名称都纳入范围。但是,当我将 MAX
的值赋给 test
时,赋值中使用的是局部变量 MAX
,因为命名空间变量 >MAX
被隐藏。局部变量优先并隐藏命名空间变量。
下面是命名空间变量和全局变量之间冲突的示例。 考虑这段修改后的代码(你可以看到它编译 here ):
const double MAX = 3.5;
namespace ns
{
const int MAX = 3;
}
using namespace ns;
int main()
{
int test = MAX;
}
同样,using
指令将 ns:MAX
引入范围,全局变量 MAX
也在范围内。
当我在 main()
中使用名为 MAX
的变量时,编译器报告错误,因为名称 MAX
现在不明确: 它无法知道我们指的是哪个 MAX
,因为有两个非本地 MAX
可供选择:两者都没有任何优先级。
prog.cpp: In function ‘int main()’:
prog.cpp:13: error: reference to ‘MAX’ is ambiguous
prog.cpp:2: error: candidates are: const double MAX
prog.cpp:6: error: const int ns::MAX
prog.cpp:13: error: reference to ‘MAX’ is ambiguous
prog.cpp:2: error: candidates are: const double MAX
prog.cpp:6: error: const int ns::MAX
关于c++ - 使用命名空间重新定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6904918/