对函数'&'的引用需要 L 值
reference to function '&' requires l-value
我有以下问题:我必须使用一个预定义函数,它需要一个调用函数的引用。
假设有一个带参数的函数:
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"然后你可以向函子传递参数同时将函子的地址传递给另一个函数
相关文章:
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 类 Referention 中C++回调函数引用非静态函数
- 使用函数引用指向节点的指针删除链表中的节点?
- 解释通过从函数引用返回数组的语法
- "Class1"类"Class2"对象作为私有数据成员。如何通过"Class 2"函数引用"Class1"对象?
- 使用默认构造函数引用成员变量初始化错误
- 无法调用函数引用 c++
- 使用 decltype(this) 获取函数引用
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 从内联函数引用文件静态变量
- Boost::将sigaction函数引用绑定到实例
- 一种比函数引用更有效的方法
- 奇怪的未定义函数引用,函数调用C++不存在
- 是否可以检测绑定成员函数引用的对象是否被删除或销毁
- 构造函数引用参数导致seg错误
- 是否可以使函数模板从函数引用中获取“decltype”
- 无法让 Lua 函数引用"self"
- 如何解析变量和函数引用(Linker & Compiler)?
- 从不同模块调用函数 - 引用错误
- 如何在主函数中连接到数据库,然后从其他函数引用它