2

有人可以解释一下是什么规则决定编译器调用f下面的仿函数而不是函数f吗?

#include <iostream>

struct A {
    void operator()() { std::cout << "functor" << std::endl; }
};

void f() { std::cout << "function" << std::endl; }

int main()  
{
    A f;
    f();  // Output: functor
}

A::operator()()并且f()不是重载,所以我的猜测是这发生在重载决议之外。

4

1 回答 1

5

那是因为名字隐藏。声明f变量时,它会隐藏f函数。在该范围内对名称的任何使用都f将引用局部变量而不是函数。

如果要调用该函数f,则可以使用范围解析运算符

#include <iostream>

struct A {
    void operator()() { std::cout << "functor" << std::endl; }
};

void f() { std::cout << "function" << std::endl; }

int main()  
{
    A f;
    ::f();  // Output: function
}
于 2013-10-21T01:15:34.957 回答