gpt4 book ai didi

c++ - 使用声明解决歧义

转载 作者:可可西里 更新时间:2023-11-01 18:29:06 28 4
gpt4 key购买 nike

看看这个片段:

namespace A {
int fn();
}
namespace B {
int fn();
}

// namespace Ns {

using namespace A;
using namespace B;
using A::fn;

int z = fn();

// }

此代码无法编译,因为 fn()int z = fn(); 处不明确

如果我将 usingz 放入命名空间(删除两个 //),代码将编译。这是为什么?全局命名空间有什么特别之处?

最佳答案

参见 [namespace.udir]/2

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace.

因此,当您拥有命名空间 Ns 时,指令 using namespace A;using namespace B 使 A::fnB::fn 出现在全局命名空间中,而 using A::fn; 使 fn 出现在 Ns。后一个声明在名称查找期间“获胜”。

关于c++ - 使用声明解决歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44894400/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com