对函数'&'的引用需要 L 值

reference to function '&' requires l-value

本文关键字:函数 引用      更新时间:2023-10-16

我有以下问题:我必须使用一个预定义函数,它需要一个调用函数的引用。

假设有一个带参数的函数:

void MyClass::UnitFunction(Unit* unit)
{
     predefinedFunction(.... , &MyClass::UnitFunction(unit), ...... );
}

当我编译这个我得到以下错误:'&' requires l-value

我真的不知道怎么解决这个问题

在这种情况下,函子可能会派上用场。我建议你读一些关于函子的东西,当你掌握了它们,你可能会重新考虑你当前所有的代码设计,它可能会证明函子正是你想要的。基本上,函子是一个重载了operator()的类。你可以把这样的对象当作一个函数,但它也可以有自己的状态和其他额外的数据保存在里面(因为它仍然是一个类对象)。

class myFunctor
{
   int state;
   //other additional data you might need
   myFunctor(int _state)
   {
      state = _state;
   }
   int operator()(int a, int b)
   {
      if(state == 0)
         return a + b;
      else if(state == 1)
         //do sth else
      ...
   }
};

那么你就可以像使用临时对象一样使用这样的函子:

myFunctor obj(0); //initialization
int a = 1, b = 2;
obj(1, 2); // calling a functor
&obj; // address of the functor, which could be used to call a function somewhere else in the code
编辑:

在你的例子中,你可以在函子的重载操作符()中返回"this"然后你可以向函子传递参数同时将函子的地址传递给另一个函数