[問題] 關於Function Pointer在Struct的用法

看板C_and_CPP作者 (WSzc)時間12年前 (2013/04/02 06:15), 編輯推噓2(207)
留言9則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC6 程式碼(Code):(請善用置底文網頁, 記得排版) 大家好, 請問一個關於Function Pointer在struct中的使用問題, 程式碼如下: struct S { int (*func_ptr)(); //function pointer } class A { int A_function1(); int A_function2(); S sTest; } int global_function1() int A:A_function2() { sTest.func_ptr = global_function1; //這行ok sTest.func_ptr = A_function1; //這行會掛,錯誤訊息如下所示 } 錯誤結果(Wrong Output): cannot convert from 'int(__thiscall A::*)()' to 'int (__cdecl *)()' 問題(Question): 請問該如何讓struct可以將function pointer指向class中的member function呢? (即為上面掛掉那行所示) 我試過是將A_function1加上static型別可以過,但因為是multi-thread的程式,宣告成 static型別會有問題,只能尋求其他方法,這樣該如何做呢? 感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 116.59.244.195 ※ 編輯: WSzc 來自: 116.59.244.195 (04/02 14:16)

04/02 14:23, , 1F
型別宣告錯了,你要寫成 int (A::*func_ptr)()
04/02 14:23, 1F

04/02 14:24, , 2F
當然這樣你就不能把它指向一般的 function
04/02 14:24, 2F

04/02 14:25, , 3F
然而member function pointer與一般function有很大差異
04/02 14:25, 3F

04/02 14:28, , 4F
這個struct是外部library的struct 可能無法更改他的型別宣告
04/02 14:28, 4F

04/02 14:28, , 5F
有辦法在不更動struct內容的情況下完成這件事嗎?
04/02 14:28, 5F

04/02 14:30, , 6F
沒辦法,你少了一個參數
04/02 14:30, 6F

04/02 14:30, , 7F
member function會幫你偷傳object位址當作this
04/02 14:30, 7F

04/02 14:31, , 8F
少了這個this你就沒辦法呼叫member function
04/02 14:31, 8F
※ 編輯: WSzc 來自: 116.59.244.195 (04/02 14:36)

04/02 14:38, , 9F
所以一定要補上 A::才行是嘛 那我可能得把struct拿出class了
04/02 14:38, 9F
文章代碼(AID): #1HMdUVRv (C_and_CPP)