函数指针试吃由于函数地址的指针。针织能够指向函数对于C/C++来说很重要也很有用,这为我们编译时未确定的顺序呢执行函数提供了另一种选择,而不需要使用条件语句。
void (*foo)(); int (*f1)(double);//传入double,返回int void (*f2)(char*);//传入char*指针,没有返回值 double* (*f3)(int,int);//返回double指针
int *f4();
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
typedef int (*funcptr)(int); ..... funcptr fptr2; fptr2 = square;
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);
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);
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);
原文地址:http://blog.csdn.net/mangoer_ys/article/details/28983823