在C++11标准之前,从类的外部获取其成员函数的指针是行不通的,除非这个函数是静态成员。
但是现代c++提供了<functional>库,使得这个路子走通了。具体例子见https://stackoverflow.com/questions/12662891/how-can-i-pass-a-member-function-where-a-free-function-is-expected
#include <functional>
#include <stdio.h>
class aClass
{
public:
void test(int x, int y)
{
printf("%d\n", x*y);
}
}
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, &a, std::placeholders::_1, std::placeholders::_2);
function1(fp);
return 0;
}
这里,由于aClass::test有两个输入变量,所以std:: bind的最后两个变量是std::placeholders:_1,std::placeholders:_2
假如另外一个类bClass要使用aClass::test,可以做如下操作:
#include <functional>
#include <stdio.h>
class aClass
{
public:
int a = 3, b = 4;
void test(int x, int y)
{
printf("%d\n", x*y+a+b);
}
};
class bClass
{
public:
bClass(std::function<void(int, int)> pfunc){
m_pfun = pfunc;
}
std::function<void(int, int)> m_pfun;
};
int main()
{
aClass a;
bClass b(std::bind(&aClass::test, &a, std::placeholders::_1,
std::placeholders::_2));
b.m_pfun(1,2);
return 0;
}