根據操作碼動態選擇並返回對應的運算函式(加/減/乘),並支援執行前回調顯示操作名稱。
int (*operation(int opnum, void (*fun)(int))) (int, int);
解讀:operation 接受 int 與函式指標 void(*)(int),返回 指向函式的指標,該函式簽名為 int (int, int)。
建議使用 typedef 簡化:
typedef int (*BinaryOp)(int, int);
typedef void (*Callback)(int);
BinaryOp operation(int opnum, Callback fun);
#include <stdio.h>
char *ops[3] = { "sum", "sub", "mul" };
int sum(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
void show(int opnum) { printf("Do the operation:%s\n", ops[opnum]); }
// 返回函式指標
int (*operation(int opnum, void (*fun)(int))) (int, int) {
fun(opnum); // 執行回調
switch (opnum) {
case 0: return sum;
case 1: return sub;
case 2: return mul;
default: return NULL;
}
}
int main() {
int a = 33, b = 17;
printf("Here a=%d, b=%d\n", a, b);
printf("\tThe result is :%d\n", operation(0, show)(a, b)); // sum
printf("\tThe result is :%d\n", operation(1, show)(a, b)); // sub
printf("\tThe result is :%d\n", operation(2, show)(a, b)); // mul
return 0;
}
Here a=33, b=17
Do the operation:sum
The result is :50
Do the operation:sub
The result is :16
Do the operation:mul
The result is :561
返回類型 (*函式名)(參數列表)。返回函式指標時,函式名被括號包裹。typedef 分層,提升可讀性與維護性。std::function<int(int,int)>:可攜帶捕獲上下文的 Lambda、綁定器、函式物件。auto 推導返回類型(C++14):auto operation(...) -> int(*)(int,int)。template<typename Op> void execute(Op op); 零開銷抽象。C 風格函式指標是底層回調機制的基石。掌握其宣告語法與 typedef 技巧,能構建靈活的動態分發系統。現代 C++ 提供更強大、類型安全的替代品,應根據專案標準選擇。