- 註冊時間
- 2012-7-22
- 最後登錄
- 2012-7-28
- 主題
- 查看
- 積分
- 94
- 閱讀權限
- 30
- 文章
- 59
- 相冊
- 0
- 日誌
- 0
 
狀態︰
離線
|
函數 亦可 當作 另一個函數 的引數, 其說明 如下。
設 一 rectangle 資料型態 如第 7 章所宣告的
struct rectangle{
struct point topLeft, bottomRight;
};
設有一函數用以計算一長方形面頂積和下:
int RectArea( struct rectangle *R)
{ return (R->bottomRight.x-R->topLeft.x)*
(R->bottomRight.y-R->topLeft.y);
}
又有一函數 ComputeArea 用以計算不同圖形的面積,其定義如下:
int ComputeArea ( void *R, int(*fp)( void*))
{ return fp(R);}
其中 R 為一指標,可用來指向一圖形,
fp 為一 函數 指標,用來 代表 一函數, fp 有一 指標參數 void * 且 return int。
註: 函數名稱 如同 陣列名稱, 可用來表一地址。
設一主程式如下:
main()
{ struct rectangle R={(0,0),(5,6)};
printf("The area of a rectangle R with top left point (%d,%d)
and bottom right point (%d,%d) is %d\n",
R.topLeft.x, R.topLeft.y, R.bottomRight.x, R.bottomRight.y,
ComputeArea(&R, RectArea));
}
執行該程式的結應為
The area of a rectangle R with top left point (0,0) and
bottom right point (5,6) is 30
|
|