我对这种情况感到困惑,谷歌搜索并没有给我答案。基本上我有以下无法编译的简单代码:
#include <iostream>
class A
{
public:
int a(int c = 0) { return 1; }
static int a() { return 2; }
};
int main()
{
std::cout << A::a() << std::endl;
return 0;
}
在编译这个时,GCC 4.2 说在 main()
中对 A::a()
的调用对于两个版本的 a()< 都是模棱两可的
有效的候选人。 Apple 的 LLVM 编译器 3.0 编译没有错误。
为什么 gcc 对我要调用哪个函数感到困惑?我认为很明显,通过使用 A::
限定 a()
我要求的是函数的 static
版本。当然,如果我删除 static
函数 a()
,这段代码仍然无法编译,因为 A::a()
不是有效的语法用于调用非static
a()
。
感谢您的任何评论!
最佳答案
这样做的原因是因为 C++ 指定这是模棱两可的。重载解析指定对于 A::a
,由于 this
不在范围内,该调用中的参数列表由 设计的 A 对象参数,而不是 *this
。重载解析不排除非静态成员函数,而是
If the argument list is augmented by a contrived object and overload resolution selects one of the non-static member functions of T, the call is ill-formed.
这已成为委员会在 core issue 1005 的背景下广泛讨论的主题。 .见 core issue 364考虑更改此规则但没有这样做。
关于c++ - 对重载静态函数的模糊调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9448951/