函数指针试吃由于函数地址的指针。针织能够指向函数对于C/C++来说很重要也很有用,这为我们编译时未确定的顺序呢执行函数提供了另一种选择,而不需要使用条件语句。
1.声明函数指针
void (*foo)();
int (*f1)(double);//传入double,返回int
void (*f2)(char*);//传入char*指针,没有返回值
double* (*f3)(int,int);//返回double指针
如果去掉第一对括号就成了返回 void* 的函数了!
下面的例子就是返回指针的函数:
int *f4();
2.使用函数指针
直接给个例子吧!
int (*fptr1)(int);
int square(int num){
return num * num;
}
int n = 5;
fptr1 = square;
printf("%d square is %d\n",n, fptr1(n));
//显示 5 square is 25
也可以这样赋值 fptr1 = □
但是没有必要那样做,因为编译器会忽略取地址符。因为函数名本来就是一个地址。
为函数指针声明一个类型定义会比较方便。通常类型定义的名字是声明的最后一个元素。
typedef int (*funcptr)(int);
.....
funcptr fptr2;
fptr2 = square;
3.传递函数指针
int add(int num1,int num2){
return num1 + 怒骂;
}
int sub(int num1,int num2){
return num1 - num2;
}
typedef int (*fptrOperator)(int,int);
int compute(fptrOperator operator, int num1, int num2){
return operator(num1,num2);
}
//调用
compute(add,5,6);
compute(sub,5,6);
4.返回函数指针
fptrOperator select(char opcode){
switch(opcode){
case '+': return add;
case '-': return sub;
}
}
int evaluate(char opcode,int num1,num2){
fptrOperator operation = select(opcode);
return operation(num1,num2);
}
//调用
evaluate('+',5,6);
evaluate('-',5,6);
5.使用函数指针数组
函数指针数组可以基于某些条件选择要执行的函数。
typedef int (*operation)(int,int);
operation operations[128] = {NULL};
void initializeOperationsArray(){
operations['+'] = add;
operations['-'] = sub;
}
int evaluateArray(char opcode,int num1,int num2){
fptrOperation operation;
operation = operations[opcode];
return operation(num1,num2);
}
//调用
initilizeOperationArray();
evaluateArray('+',5,6);