直接上例子,参考Effective c++ 和 https://blog.csdn.net/chdhust/article/details/8006601
#include <iostream>
#include <iomanip>
#include <tr1/memory>
#include <tr1/functional>
//std::tr1::function 可以对静态成员函数进行绑定
//std::tr1::bind 可以对非静态成员函数进行绑定
//指向虚成员函数,可以实现函数重载
typedef std::tr1::function<void (int)> HandlerEvent;
//然后再定义一个成员变量
class Sharp{
public:
HandlerEvent handlerEvent;
};
//然后在其它函数内就可以通过设置handlerEvent的值来动态装载事件响应函数了,如:
class Rectangle{
private:
std::string name;
Sharp sharp;
public:
void initial(void);
void initial_1(void);
void initial_2(void);
const Sharp getSharp() const;
static void onEvent(int param){
std::cout << "invode onEvent method,get parameter: " << param << std::endl;
}
void onEvent_1(int param){
std::cout << "invode onEvent method,get parameter: " << param << std::endl;
}
virtual void onEvent_2(int param){
std::cout << "invode Rectangle's onEvent method,get parameter: " << param << std::endl;
}
};
//类的实现方法
void Rectangle::initial(){
sharp.handlerEvent = std::tr1::function<void (int)>(&Rectangle::onEvent);
//sharp.handlerEvent = HandlerEvent(&Rectangle::onEvent);
std::cout << "invode initial function!" << std::endl;
}
void Rectangle::initial_1(){
sharp.handlerEvent = std::tr1::bind(&Rectangle::onEvent_1, this, std::tr1::placeholders::_1);
//因onEvent函数需要一个参数,所以用一占位符,这里相当于int param这个参数
std::cout << "invode initial function!" << std::endl;
}
void Rectangle::initial_2(){
sharp.handlerEvent = std::tr1::bind(&Rectangle::onEvent_2, this, std::tr1::placeholders::_1);
std::cout << "invode initial function!" << std::endl;
}
const Sharp Rectangle::getSharp() const{
return sharp;
}
class Square : public Rectangle{
public:
void onEvent_2(int param){
std::cout << "invode Square's onEvent method,get parameter: " << param << std::endl;
}
};
//下面为测试函数:
int main(int argc,char *argv[]){
Rectangle rectangle;
rectangle.initial();
rectangle.getSharp().handlerEvent(23);
Rectangle rectangle_1;
rectangle_1.initial_1();
rectangle_1.getSharp().handlerEvent(24);
Rectangle rectangle_2;
rectangle_2.initial_2();
rectangle_2.getSharp().handlerEvent(25);
Square square;
square.initial_2();
square.getSharp().handlerEvent(26);
return 0;
}
结果呈现:
invode initial function!
invode onEvent method,get parameter: 23
invode initial function!
invode onEvent method,get parameter: 24
invode initial function!
invode Rectangle’s onEvent method,get parameter: 25
invode initial function!
invode Square’s onEvent method,get parameter: 26