SOGO論壇

標題: 函數的函數參數 [列印本頁]

作者: 108    時間: 2012-7-23 08:46:25     標題: 函數的函數參數

函數 亦可 當作 另一個函數 的引數, 其說明 如下。
設 一 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






歡迎光臨 SOGO論壇 (https://oursogo.com/) Powered by OURSOGO.COM