精華區beta C_and_CPP 關於我們 聯絡資訊
: : void (*test1(int in))(int){ : 請問這行的宣告, 是什麼意思呢? test1 是一個 function, 他吃一個 int 參數 // test1(5); // => call test1 傳回值是一個 function pointer, 型別是: void (*)(int), 也就是沒有傳回值,吃一個 int 參數 // void (*pf)(int) = test1(5); // => pf 指向 test1 的傳回值 : : printf("test1 is called by %d\n", in); : : return &test2; : 我如果把這裡改成 : return; : 他會告訴我 " 程式記憶體區段錯誤 " 嗯?我會編譯錯誤說 應該沒道理可以編譯,型別會不相符 : 但是小弟實在是對這一段 code 不是很了解. : test(5)(10) 這樣子的寫法, 是什麼意思呢? void (*pf)(int) = test1(5); pf(10); 這樣會不會比較好懂? :) 簡單說就是我直接呼叫他傳回的 function 沒有拿一個變數去把他存起來 假使我寫成這樣:(不要頭昏喔 XD) void (*(*test0(int in))(int))(int){ printf("test0 is called by %d\n", in); return &test1; } 然後改成這樣 call: test0(5)(10)(15); /* output result: test0 is called by 5 test1 is called by 10 test2 is called by 15 */ 我的 test0 傳回一個 function pointer 指向一個傳入是 int, 傳出是一個 function pointer, 這個 f.. p.. 的傳入是 int, 傳出是一個 f.. p.. 指向一個傳入是 int, 傳出是 void 的 function 呃,我想我中文表達得很差,建議看 code 測試幾次比較容易懂 總之就是一個 pf 串一個 pf 就是了 如果能改成 functor 來看的話會更容易懂(如果是 C++ 的話) void test2(int in){ } Functor test1(int in){ return &test2; } Functor test0(int in){ return &test1; } test0(5)(10)(15); // 等同於: Functor f1 = test0(5); Functor f2 = f1(10); f2(15); // 等同於: void (*(*pf1)(int))(int) = test0(5); void (*pf2)(int) = pf1(10); pf2(15); : 翻了一兩本書, 好像都沒有提到相關的寫法 Orz ..... 我想這些東西都是技巧,多練習比較容易熟悉 你還沒貼這篇之前我也沒想過這樣玩 XD -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ※ 編輯: godfat 來自: 220.132.128.238 (02/04 18:44)
drkkimo:解釋的很清楚呀 02/04 19:50
lightspeed:推薦這篇文章 02/04 21:05
inses:推,其實重點就是把return type抓出來,一層層頗析 02/04 21:17
chy168:Cool~ 我懂了, 感謝您~ :pp 02/04 22:52