[問題] 在struct中宣告function

看板C_and_CPP (C/C++)作者 (AG)時間14年前 (2011/12/09 20:53), 編輯推噓3(3010)
留言13則, 4人參與, 最新討論串1/1
想請問大家怎麼樣在struct 裡頭宣告 function 接著來使用這個function呢? #include <iostream> #include <string.h> #include <stdlib.h> using namespace std; typedef struct F{ int l; int(* printem) (string text ); }F; int main(){ F a; a.printem("123"); } 這是我的code 可以順利compile 但在run time會crash 似乎是因為memory access的問題, 請問大家是哪裡有誤呢? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.169.178.204

12/09 21:00, , 1F
google : function pointer. printem 本身是函式指標,
12/09 21:00, 1F

12/09 21:00, , 2F
...... 你的函式寫在哪...
12/09 21:00, 2F

12/09 21:01, , 3F
這只是一個指標 不是物件...
12/09 21:01, 3F

12/09 21:05, , 4F

12/09 21:06, , 5F
21 行改 cout << obj2.printem("01234") << endl;
12/09 21:06, 5F

12/09 21:11, , 6F
寫C++拜託不要再寫 typedef struct F {...} F;
12/09 21:11, 6F

12/09 21:13, , 7F
typedef struct tagF {...} F; ????
12/09 21:13, 7F

12/09 21:14, , 8F
不需要 typedef 啊,struct F{...}; 寫完 F 就是個type
12/09 21:14, 8F

12/09 21:15, , 9F
之所以要 typedef 是 C 本身的限制,C++ 沒有這種限制
12/09 21:15, 9F

12/09 21:16, , 10F
謝謝指導 :)
12/09 21:16, 10F

12/09 21:41, , 11F
因為我這個function 直接return, 所以就沒附上內容
12/09 21:41, 11F

12/09 21:41, , 12F
謝謝各位 我研究一下
12/09 21:41, 12F

12/09 21:45, , 13F
看來我有點誤會了 謝謝tropical72 的範例
12/09 21:45, 13F
文章代碼(AID): #1EuWI_wn (C_and_CPP)
文章代碼(AID): #1EuWI_wn (C_and_CPP)