#include <iostream>
void fun1(void) {
std::cout << "fun1" << std::endl;
}
int fun2(int n) {
return 0;
}
int main(void)
{
void (*f1Ptr)(void) = fun1;
int (*f2Ptr)(int) = fun2;
f1Ptr();
std::cout << f2Ptr(1) << std::endl;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:fundemo17.cpp
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2013 年 1 月 */第 13 行與第 14 行分別定義函數指標,留意函數指標的寫法,先是函數的回傳值 (return value) 型態 (type) ,然後用小括弧圍住帶星號的識別字 (identifier) ,後面則是小括弧與參數列 (parameter list)
void (*f1Ptr)(void) = fun1; int (*f2Ptr)(int) = fun2;
這是說,函數指標只能指向具有相同回傳值型態與參數列的函數。
下面利用函數指標呼叫函數
f1Ptr(); std::cout << f2Ptr(1) << std::endl;
編譯執行結果如下

| 中英文術語對照 | |
|---|---|
| 函數 | function |
| 指標 | pointer |
| 呼叫 | call |
| 函數指標 | function pointer |
| 回傳值 | return value |
| 型態 | type |
| 識別字 | identifier |
| 參數列 | parameter list |
您可以繼續參考
函數
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言