一、回调函数:
回调函数就是一个通过函数指针调用的函数,如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方,而是在特定的事件或条件发生时有另一方调用的,用于该事件或条件进行相应。
二、代码实现:
1:冗余版本:
#include void menu(){printf("*********************************\n");printf("********* 1:Add2:Sub ********\n");printf("********* 3:Mul4:Div ********\n");printf("********* 0:exti ********\n");printf("*********************************\n");}int Add(int x, int y){return x + y;}int Sub(int x, int y){return x - y;}int Mul(int x, int y){return x * y;}int Div(int x, int y){return x / y;}int main(){int input = 0;do{int x = 0;int y = 0;menu();printf("请选择:>");scanf("%d", &input);switch (input){case 1:printf("请输入两个操作数!\n");scanf("%d %d", &x, &y);printf("%d\n", Add(x,y));break;case 2:printf("请输入两个操作数!\n");scanf("%d %d", &x, &y);printf("%d\n", Sub(x, y));break;case 3:printf("请输入两个操作数!\n");scanf("%d %d", &x, &y);printf("%d\n", Mul(x, y));break;case 4:printf("请输入两个操作数!\n");scanf("%d %d", &x, &y);printf("%d\n", Div(x, y));break;case 0:printf("退出计算器!\n");break;default:printf("选择错误!");break;}} while (input);return 0;}
2:回调函数版本
#include void menu(){printf("*********************************\n"); printf("********* 1:Add2:Sub ********\n");printf("********* 3:Mul4:Div ********\n");printf("********* 0:exti ********\n");printf("*********************************\n");}int Add(int x, int y){return x + y;}int Sub(int x, int y){return x - y;}int Mul(int x, int y){return x * y;}int Div(int x, int y){return x / y;}void calc(int (*pf)(int, int))//此时用回调函数的方法简化代码。{ //回调函数:一个通过函数指针调用的函数。所以Add、Sub、Mul、Div,被称为回调函数。int x = 0;int y = 0;int ret = 0;printf("请输入两个操作数!\n");scanf("%d %d", &x, &y);ret = pf(x, y);printf("%d\n", ret);}int main(){int input = 0;do{menu();printf("请选择:>");scanf("%d", &input);switch (input){case 1:calc(Add);break;case 2:calc(Sub);break;case 3:calc(Mul);break;case 4:calc(Div);break;case 0:printf("退出计算器!\n");break;default:printf("选择错误!");break;}} while (input);return 0;}
3:转移表实现
#include void menu(){printf("*********************************\n"); printf("********* 1:Add2:Sub ********\n");printf("********* 3:Mul4:Div ********\n");printf("********* 0:exti ********\n");printf("*********************************\n");}int Add(int x, int y){return x + y;}int Sub(int x, int y){return x - y;}int Mul(int x, int y){return x * y;}int Div(int x, int y){return x / y;}int (*pf[5])(int, int) = { NULL,Add,Sub,Mul,Div };//函数指针数组存放上述指针的地址 - 转移表int main(){int input = 0;int x = 0;int y = 0;int ret = 0;do{menu();printf("请选择:>");scanf("%d\m", &input);if(input == 0){printf("退出计算器\n");break;}else if (input >= 1 && input ");scanf("%d %d", &x, &y);ret = pf[input](x, y);printf("%d\n", ret);}else{printf("选择错误!");}} while (input);return 0;}