【问题标题】:Compiler chooses functor over function with same name编译器选择仿函数而不是具有相同名称的函数
【发布时间】:2013-10-21 01:12:07
【问题描述】:

谁能解释一下是什么规则决定了编译器调用下面的函子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() 不是重载,所以我猜这发生在重载决议之外。

【问题讨论】:

    标签: c++ function functor


    【解决方案1】:

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

    如果你想调用函数f,那么你可以使用scope resolution operator

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

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多