c++ - 对重载静态函数的模糊调用

标签 c++

我对这种情况感到困惑,谷歌搜索并没有给我答案。基本上我有以下无法编译的简单代码:

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

相关文章:

c++ - 这个模板特化或声明(或其他东西)?

c++ - QPieSlice的Qt坐标

c++ - 按值返回对象 vector

java - 在 Java 中命名两种作用域

c++ - 调试这个c++程序

c++ - 为什么 std::allocator::deallocate 需要大小?

c++ - 将 HEX 转换为可打印的字符串/字符

c++ - "Conditional"解析命令行参数

c++ - CMake 和 wxWidgets 2.9.5

c++ - 如何访问 Windows Mobile 设备的加速度计?