![]() |
|
||||||
指向成员函数的指针并非指针,是一个类内偏移加1 non-static函数,不能用作回调函数,因为函数的第一个参数是隐含的this指针,所以与回调类型不匹配了。 再加一个m_pthis指针上去,用于保存所指对象,这样就可以避免你所说的单一的static了。不过,要使用具体哪个对象的回调函数前,必须reset()一下static的那个指针值:),当然也可以把reset()放在构造函数里。 修改过的代码如下: // DosTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; typedef void( *CFUNC )( int,int ); void DoSomeThing( CFUNC pFunc ){ pFunc( 10, 20 ); } class CMyClass{ public: void DoThing( int i,int j ){ cout<< i <<' '<< j<<endl; } }; // CallBack of CMyClass 的封装。 class cb_CMyClass{ typedef void ( CMyClass::* C_MFUNC )( int, int ); static CMyClass* pthis; static C_MFUNC pfunc; // 回调函数。 用当前注册的 pthis 调用 当前注册的 pfunc static void cb_func( int i, int j ) { if ( pthis && pfunc ) ( pthis->*pfunc )( i, j ); } public: // get_CallBack, 设置属性并返回回调函数。 // 缺点是,属性保存为全局变量,一次只能设置一个回调函数 static CFUNC getCB( C_MFUNC pf ) { pfunc = pf; return cb_func; } //---------------------------------------------- public: explicit cb_CMyClass(CMyClass& pt):m_pthis(&pt) {} void reset() { pthis = m_pthis; } private: CMyClass* m_pthis; }; CMyClass* cb_CMyClass::pthis; cb_CMyClass::C_MFUNC cb_CMyClass::pfunc; int main(){ CMyClass c; // cb_CMyClass::getCB 返回一个回调函数指针。 // 他的参数是:设置当前 CMyClass 对象,以及需要回调的函数 // 但是:注意! 他们都是static成员。 所以这两个数据只有一套! // 下次使用就会覆盖上次 this 和 func 设置! /* modified by igray * 添加了一个成员变量来保存对象状态和reset()函数来重置static的pthis */ cb_CMyClass cb_wrapper(c); cb_wrapper.reset(); DoSomeThing( cb_CMyClass::getCB( &CMyClass::DoThing ) ); } |
|||||||
|
|||||||
| XP中如何限制“我最近的文档” < 上一篇 | 下一篇 > 万能型电视遥控器代码表 |
用户回复
