close

看了網路上[1]有關Function Pointer, 感覺Function Pointer使用語法很累贅, 於是聯想到typedef來簡化

原本累贅的語法

double (*PtrFun)(double a, double b)

只要前面多加一個typedef, 呼叫上就會變得比較親民

typedef double (*PtrFun)(double a, double b)

例如我想要一個四則運算的功能

PtrFun p[4]{ OperatorAdd, OperatorSub, OperatorMul, OperatorDev };

宣告一個PtrFun資料型態,存放四個函式指標(即為函式名稱)

OperatorAdd, OperatorSub, OperatorMul, OperatorDev

   1: #include "stdafx.h"
   2: #include <stdio.h>
   3: #include <iostream>
   4:  
   5: typedef double (*PtrFun)(double a, double b);
   6: using namespace std;
   7: double OperatorAdd(double a, double b);
   8: double OperatorSub(double a, double b);
   9: double OperatorMul(double a, double b);
  10: double OperatorDev(double a, double b);
  11:  
  12: int main()
  13: {
  14:     int i;
  15:     double a = 4, b = 2;
  16:     char* info[4] = { "+","-","x","/" };
  17:     PtrFun p[4]{ OperatorAdd, OperatorSub, OperatorMul, OperatorDev };
  18:     for (i = 0; i < 4; i++)
  19:     {
  20:         cout << a << info[i] << b << " = " << p[i](a, b) << endl;
  21:     }
  22:     
  23:     return 0;
  24: }
  25:  
  26: double OperatorAdd(double a, double b)
  27: {
  28:     return a + b;
  29: }
  30: double OperatorSub(double a, double b)
  31: {
  32:     return a - b;
  33: }
  34: double OperatorMul(double a, double b)
  35: {
  36:     return a*b;
  37: }
  38: double OperatorDev(double a, double b)
  39: {
  40:     double ret = (b == 0 ? 0 : a / b);
  41:     return ret;
  42: }

image


參考資料

1. C - Function Pointer

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()