这是代码示例:
namespace A
{
int k;
}
void k(int,int){/*dosomething*/}
int main()
{
using namespace A;
k(1,1);//ooop!k is ambiguous!
}
发生了什么事?我认为这不应该是模棱两可的,因为它们是不同的类型。为什么会模棱两可?使用 int k
不可能执行 k(1,1)
。
所以它与名称实际是什么无关?即使不是函数类型的名称也会在我们使用 k(1,1)
时引起歧义,这是错误的在语法中因为 int k
不是函数?
最佳答案
查找名称 k
是不明确的,因为有两个匹配的声明可见,::k
和 ::A::k
。
确切的规则可以在 C++ 标准 (N4659 [basic.lookup]/1) 中找到:
Name lookup associates the use of a name with a set of declarations of that name. The declarations found by name lookup shall either all declare the same entity or shall all declare functions; in the latter case, the declarations are said to form a set of overloaded functions.
查找用于函数调用的非限定名称有两个阶段:
- 名称的不合格查找
- 名称的参数相关查找。
非限定名称查找规则,即使在查找用于函数调用的名称时,也能找到该名称的任何声明。(规则不是它只搜索函数声明那个名字)。此阶段同时查找 ::k
和 ::A::k
,无论它们是函数、int
还是其他。
依赖于参数的查找确实有一个规则,即只为查找的那部分找到函数声明。但这与此代码无关。
using
指令的相关行为包含在 [basic.lookup.unqual]/2 中(由我编辑,仅显示与该问题相关的部分):
For the purpose of the unqualified name lookup rules, the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace.
这澄清了 using namespace A;
实际上并没有将 A
的成员引入到 main()
的范围内;但这意味着当在全局命名空间中查找名称时(因为这是 using 声明站点的最内层封闭命名空间),A
中的名称也将在那里找到。
关于c++ - 为什么 int 对象和函数类型之间存在歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312133/