函數指針,即:通過指針變量引用函數(拿到函數在記憶體中的起始位址,也即:函數執行的入口位址),通過函數指針不僅可以實作函數的間接調用;而且,将函數指針作為函數參數進行傳遞,還可以實作C語言下-相對于同一個函數指針在獨立功能子產品下的多态複用。舉例如下,
#include <stdio.h>
#include <stdlib.h>
int (*pFunc)(int m,int n);
int (*pFunc1)(char*);
int maxVal(int m,int n);//求最大值
int minVal(int m,int n);//求最小值
void solveMsg(char* msg,void (*pFunc)(char*));//處理消息
void solveMsg(char* msg,int (*pFunc)(char*)){
pFunc(msg);
}
int sloveMode1(char* msg){
puts(msg);
printf("處理模式1\n");
return 1;
}
int sloveMode2(char* msg){
puts(msg);
printf("處理模式2\n");
return 1;
}
int main(int argc,char** argv){
char *str="Hello,World!\t";
//2-函數指針
pFunc=&maxVal;
printf("%d\n",pFunc(12,2));
//修改函數指針
pFunc=&minVal;
printf("%d\n",pFunc(12,2));
//1-函數指針作為函數參數
pFunc1=&sloveMode1;
solveMsg(str,pFunc1);
pFunc1=&sloveMode2;
solveMsg(str,pFunc1);
return 0;
}
//求最大值
int maxVal(int m,int n){
return m>n?m:n;
}
//求最小值
int minVal(int m,int n){
return m<n?m:n;
}
