加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:36:25 所属栏目:百科 来源:网络整理
导读:// main.cppconst double MAX = 3.5;namespace ns{ const int MAX = 3;}int main(){} 这会导致重新定义错误吗? 我指的是this MSDN page,它在备注部分说这是一个错误. 更新:我想在复制代码时可能会遗漏一个重要声明. using ns::MAX; 解决方法 不 – 我不知
// 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读