旧的函数指针我们就不要讲了,过时了。
新的方法如下(c++11):
1、使用lambda表达式
2、结合std::bind和std::function
示例,一看就会,不看还真要找半天:
#include <stdio.h>
#include <iostream>
#include <functional>
//声明未初始化的function函数包装器
typedef std::function<void(int)> Fun;
class Bird{
public:
Bird(){}
// 我们就是想尽办法调这个move函数,还是非静态的!
void move(int h){
std::cout<<"I am flying:"<<h<<std::endl;
}
};
// 调用者示例
class Caller{
public:
void callOthers(Fun cb){
if(cb != nullptr)
cb(3);
}
};
int main()
{
Bird bird;
//2.把实例化的对象和成员函数绑定,函数指针赋值给function
Fun fun = std::bind(&Bird::move,&bird,std::placeholders::_1);
// 直接调用函数
fun(2);
Caller call;
// 或者传给另一个函数内部进行调用
call.callOthers(fun);
// 使用lambda表达式进行回调
auto lamb = [&](int h){
bird.move(h);
};
call.callOthers(lamb);
return 0;
}
实际一句话:需要知道类对象的地址,这样就知道了类的成员地址,这样就可以调用这个函数了。输出:
I am flying:2 I am flying:3 I am flying:3
简单吧,比那些联合函数、boost啥的简单多了