c++ - 使用命名空间重新定义错误

标签 c++ namespaces

// 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/

相关文章:

c - C 中的命名空间

php - 在 PHP 中为 stdClass 对象设置命名空间

c++ - 如何让所有平台编译器为 NaN 输出相同的字符串?

c++ - 双三次图像调整算法

c++ - const 到非常量指针模板参数转换

c++ - 为什么使用构造函数而不是函数?

c++将给定.dat文件中的字符串 vector 转换为 double vector

c++ - rand() 为什么以及如何存在于 cstdlib 的全局和 std 命名空间中?

namespaces - 使用标识符创建 URI 的良好做法

ruby-on-rails - 添加 Admin 命名空间时的路由错误