
函數也可以用指標來呼叫,這樣的指標被稱為函數指標,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | void fun1(void) { |
| 004 | std::cout << "fun1" |
| 005 | << std::endl; |
| 006 | } |
| 007 | |
| 008 | int fun2(int n) { |
| 009 | return 0; |
| 010 | } |
| 011 | |
| 012 | int main() { |
| 013 | void (*f1Ptr)(void) = fun1; |
| 014 | int (*f2Ptr)(int) = fun2; |
| 015 | |
| 016 | f1Ptr(); |
| 017 | std::cout << f2Ptr(1) |
| 018 | << std::endl; |
| 019 | |
| 020 | return 0; |
| 021 | } |
| 022 | |
| 023 | /* Kaiching Chang |
| 024 | u0809.cpp |
| 025 | 2014-02 */ |
第 13 行與第 14 行分別定義函數指標,留意函數指標的寫法,先是函數的回傳值型態,然後用小括弧圍住帶星號的識別字,後面則是小括弧與參數列
| 013 | void (*f1Ptr)(void) = fun1; |
| 014 | int (*f2Ptr)(int) = fun2; |
這是說,函數指標只能指向具有相同回傳值型態與參數列的函數。
下面利用函數指標呼叫函數
| 016 | f1Ptr(); |
| 017 | std::cout << f2Ptr(1) |
編譯執行,結果如下
| $ g++ u0809.cpp |
| $ ./a.out |
| fun1 |
| 0 |
| $ |
continue ...
沒有留言:
張貼留言