我在使用时遇到了一些问题 std::function
它适用于 static intfuncAB
但实际上,我需要类中非静态的 std 函数。
#include <functional>
#include <iostream>
class test{
public:
std::function<int (int, int)> func;
int funcAB(int a, int b){
return a + b;
}
test(){
func = test::funcAB;
}
};
int main(){
using namespace std;
test A;
cout <<A.funcAB(10,11) << endl;
cout <<A.func(11,12) << endl;
}
错误:
main.cpp:11:22: error: invalid use of non-static member function ‘int test::funcAB(int, int)’
func = test::funcAB;
^~~~~~
这里有两个问题:
首先是要获得指向成员函数的指针,您需要使用 address-of 运算符&
。如&test::funcAB
.
另一个问题是非静态成员函数需要调用一个对象。如果您没有对象,则无法调用它。
要解决第二个问题,请使用 std::bind
using namespace std::placeholders; // for _1, _2, _3...
func = std::bind(&test::funcAB, this, _1, _2);
或者使用lambda
func = [this](int a, int b)
{
return funcAB(a, b);
};
通常推荐使用 Lambda 超过std::bind
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句