[問題] 成員函數指標一問

看板C_and_CPP作者 (!?)時間12年前 (2012/07/20 18:28), 編輯推噓0(002)
留言2則, 1人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux GCC 預期的正確結果(Expected Output): 透過呼叫computing, 投入運算對應的指標函數 並由此函數得到運算結果. 錯誤結果(Wrong Output): MathMachine.cpp: In function ‘int main()’: MathMachine.cpp:27:46: error: no matching function for call to ‘ MathMachine::computing(int, int, int (MathMachine::*&)(int, int))’ MathMachine.cpp:18:5: note: candidate is: int MathMachine::computing(int, int, int (*)(int, int)) 程式碼(Code):(請善用置底文網頁, 記得排版) [ MathMachine.h ] using namespace std; class MathMachine { public: MathMachine(); int add(int, int); int sub(int, int); int mul(int, int); int computing(int , int, int (*) (int, int)); }; [ MathMachine.cpp ] #include <iostream> #include "MathMachine.h" using namespace std; int MathMachine::add(int x, int y){ return x+y; } int MathMachine::sub(int x, int y){ return x-y; } int MathMachine::mul(int x, int y){ return x*y; } int MathMachine::computing(int x, int y, int (*ptr)(int, int)){ return (*ptr)(x, y); } int main(){ MathMachine math; int (MathMachine::*ptr)(int, int)=0; ptr = &MathMachine::add; int result = math.computing(1, 2, ptr); cout << "the result is : " << result << endl; return 0; } 補充說明(Supplement): 有人跟我說用__thiscall 但gcc下好像沒這東西@@? 請問這該如何改才對呢? 謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.34.18.97

07/20 18:55, , 1F
在這邊用物件包起來只是徒增煩惱而已
07/20 18:55, 1F

07/20 18:56, , 2F
不如直接用static function
07/20 18:56, 2F
文章代碼(AID): #1G2JB1Av (C_and_CPP)
文章代碼(AID): #1G2JB1Av (C_and_CPP)