一句话总结:利用boost::bind可以让回调函数更加灵活易用,不局限于函数类型及参数个数;然后无法像面向对象的虚函数那样可以一类功能中灵活扩展。
#include <iostream>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
typedef boost::function<void ()> FunCallback_;
class Parent : boost::noncopyable
{
public:
Parent(int tall):tall_(tall){}
~Parent(){}
void setFunCallback(const FunCallback_& cb)
{
funcallback_ = cb;
}
void start()
{
printf("parent tall:%d\n", tall_);
funcallback_();
}
private:
FunCallback_ funcallback_;
int tall_;
};
class Child : boost::noncopyable
{
public:
Child(int age)
:age_(age),
parent_(180)
{
parent_.setFunCallback(boost::bind(&Child::print, this));
}
~Child(){}
void print()
{
printf("I am child!\n");
}
void start()
{
parent_.start();
}
private:
int age_;
Parent parent_;
};
class Child2 : boost::noncopyable
{
public:
Child2(int age)
:age_(age),
parent_(170)
{
parent_.setFunCallback(boost::bind(&Child2::print, this));
};
~Child2(){}
void print()
{
printf("I am child2!\n");
}
void start()
{
parent_.start();
}
private:
int age_;
Parent parent_;
};
int main(int argc, const char * argv[]) {
// insert code here...
Child child(22);
Child2 child2(23);
child.start();
child2.start();
return 0;
}
parent tall:180
I am child!
parent tall:170
I am child2!
Program ended with exit code: 0