看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《EdisonX (卡卡獸)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : vs2010 : 問題(Question): : 我想在自己的 class Display 實現 callback 功能 , 讓其他 class 使用 : 目前我想比較正式的方法應該是用 template 方式去做,但這份 : class 要改成 template 的話有些工程,故想加上 function pointer 方式去做, : 但發現好像不能塞其他 class 之 member function, : 問題之程式碼簡化如下, : 同步附 Code http://codepad.org/nT3XDA5q : ////// : class Display : { : private: : void (*m_CallBackFunc)(int) ; : public: : Display( void (*CallBackFunc)(int) = NULL) : : m_CallBackFunc( CallBackFunc ) : { : } : void ToUpdateDisplay(int iSel) : { : if(m_CallBackFunc) : if(rand() & 1) // some condition here : m_CallBackFunc(iSel); : } : }; class Display { private: void ( PlaneDlg::*m_CallBackFunc )(int); PlaneDlg *m_P; public: Display( void ( PlaneDlg::*CallBackFunc )(int), PlaneDlg *P ) : m_P( P ), m_CallBackFunc( CallBackFunc ) { } void ToUpdateDisplay( int iSel ) { if( m_CallBackFunc && m_P ) if( rand() & 1 ) ( m_P->*m_CallBackFunc && m_P )( iSel ); } class PlaneDlg { private: Display m_display; public: PlaneDlg(): m_display( this, &::UpdateDisplay ) { } void UpdateDisplay( int iGrp ) { //.... } } 這樣試看看, 人在外面不能測試XD : /////// : class PlaneDlg : { : private: : Display m_display; : public: : PlaneDlg () : : m_display ( UpdateDisplay ) // <- 人是它殺的 ... : // : m_dysplay ( & PlaneDlg :: UpdateDisplay) // 這樣還是救不了它 .. : { : } : void UpdateDisplay(int iGrp) : { : // do something.. : } : }; : 上述黃色部份我不知道該怎麼才能讓它過 , : vs 的錯誤訊息是 : 'Display::Display(,void (__cdecl *)(int))' : 無法將參數 2 從 'void : (__thiscall PlaneDlg::* )(int)' 轉換成 'void (__cdecl *)(int)' : 希望能動到最小的 Display ,去實現這個功能。 : 另也希望版友能針對此問題提供一些架構上的意見, : 避開日後同樣的問題再重現。 : 非常感謝各位! -- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.24.201 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1437144958.A.EB1.html
EdisonX: 謝謝,這方法是可行,只是考慮到 Display 可能不只讓一個 07/17 22:57
EdisonX: class 使用/包含 , 後來發現這種架構維護不易, 謝謝回覆. 07/17 22:58
notBeing: 那就要用template啦 07/17 23:41