在C++开发中,有很多时间会使用到回调函数,每次函数都要求是全局函数(类的静态函数也可以)。最近由于工作的原因,接触到SOUI界面库的自定义事件,他提供的注册机制非常特别,可绑定类的私有成员方法。理解他的实现后,写下这篇绑定私有函数的demo,以作记录。
class TestA;
class TestB
{
Publib:
typedef int (TestA::*MumberFuncType)():
TestB(){}
void RunAFun()
{
(object_->*func)();
}
void RegistAFunc(TestA* o,MumberFuncType fn)
{
object=o;
func_=fn;
}
private:
MumberFuncType func_;
TestA* object_;
};
class TestA
{
public:
TestA()
{}
void RegistFunToB(TestB* b)
{
b->RegistAFunc(this,&TestA::func);
}
private:
int func()
{
int i=100;
return i;
}
};
int main()
{
TestA a;
TestB b;
a.RegistFunToB(&b);
b.RunAFun();
return 0;
}
大家知道怎么修改才能真正用于项目中吗?做个提示,TestA是接受事件的类,将TestA 和 MwmberFuncType 组合成一个对象(使用模块创建这个子类,TestB通过父类指针操作)。
详见我的博客:C++绑定私有函数扩展(使用模板类)