看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《QgameQ (123)》之銘言: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.37.104.132
dendrobium:試試看錯誤訊息講的那個吧... 04/09 18:15
james732:void (*f)(); 改成 void (*f)(A *); 呢? 04/09 18:15
james732:喔喔別理我 XD 04/09 18:15
dendrobium:應該是void (A::*f)(); 吧 04/09 18:15
改成這樣後報錯是: 1.`void (A::)()' does not match `void (A::*)()' 2.must use .* or ->* to call pointer-to-member function in `f (...)' 恩...有點接近卻不知道怎麼改才對
james732:可參考 http://0rz.tw/bUcG9 04/09 18:30
dendrobium:void (A::*f)() = &A::run; //這樣呢? 04/09 18:51
改成這樣後可以塞入 但執行f()結果有報錯2. ※ 編輯: QgameQ 來自: 114.37.104.132 (04/09 21:48) 你對 member function 的認知少了一項重要的觀念 那就是 this pointer 所以你會覺得後面的 f() 不能呼叫很奇怪 簡單講 如果你這樣寫 class A { public: void run() { cout << data << endl; } private: int data; }; void (A::*f)() = &A::run; f(); 那請問,執行到 cout << data << endl 的時候 那個 data 是哪一份 A 物件的 data 呢? 所以你透過 member function pointer 呼叫 member function 的時候 要提供一份物件 A a; (a.*f)(); 如果你覺得這樣很麻煩 (我也覺得很麻煩,C++ 應該提供 delegate 的) 有個辦法是用另一個 class 把物件與 member function pointer 包起來 class AFunctor { public: AFunctor(A& a, void (A::*f)()) : obj(a), func(f) {} void operator()() { (obj.*func)() } private: A& obj; void (A::*func)(); }; AFunctor f(a, &A::run); // ... // ... f(); // calls a.run() -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.76.157
VictorTom:推. 04/09 22:54
nowar100:push 04/10 00:48
QgameQ:謝謝^^ 04/10 03:31
yoco315:另外推這個 http://codeplea.com/pluscallback O_O 04/11 18:13
yoco315:目前看到完程度最高的 functor class 04/11 18:13