函数指针的用途:转移表
ps:因为重点是转移表,所以函数类型都是一样的 int ,就无法实现小数的运算了
#include
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 menu()
{
printf(
"****************************\n"
"********请选择:>************\n"
"*****1.Add 2.Sub**********\n"
"*****3.Mul 4.Div**********\n"
"****************************\n");
}
int main()
{
int x = 0, y = 0, choice = 0;
do
{
menu();
printf("请选择:\n");
scanf("%d", &choice);
printf("请输入操作数:\n");
switch (choice)
{
case 0:
printf("退出计算器\n");
break;
case 1:
scanf("%d %d", &x, &y);
Add(x, y);
printf("结果是:%d\n", Add(x, y));
break;
case 2:
scanf("%d %d", &x, &y);
Sub(x, y);
printf("结果是:%d\n", Sub(x, y));
break;
case 3:
scanf("%d %d", &x, &y);
Mul(x, y);
printf("结果是:%d\n", Mul(x, y));
break;
case 4:
scanf("%d %d", &x, &y);
Div(x, y);
printf("结果是:%d\n", Div(x, y));
break;
default:
printf("输入错误,重输!\n");
}
} while (choice);
}
发现这样写非常冗余
先介绍函数指针数组:
是存放函数指针的数组
初始化形式:
int (*arr[5])()=__
arr先与 [5]结合表示是一个数组
数组的内容是 int (*)( )类型的函数指针,也就是函数指针数组只能存放相同类型的函数指针
#include
void menu()
{
printf(
"****************************\n"
"********请选择:>************\n"
"*****1.Add 2.Sub**********\n"
"*****3.Mul 4.Div**********\n"
"****************************\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 choice = 0, x = 0, y = 0;
do
{
menu();
printf("请选择:\n");
int (*p[5])(x, y) = { 0,Add,Sub,Mul,Div };//转移表
scanf("%d", &choice);
if (choice >= 1 && choice <= 4)
{
printf("请输入操作数:\n");
scanf("%d %d", &x, &y);
int ret = (*p[choice])(x, y);//或者:p[choice](x,y)
printf("结果是:%d\n", ret);
}
else if (choice == 0)
{
printf("退出计算器\n");
break;
}
else
printf("输错啦,重输!\n");
} while (choice);
return 0;
}
int ret = (*p[choice])(x, y);
(*p[choice]) 表示函数名 ( 也可以写成p[choice] ),(x,y)表示要传过去的实参
回调函数:如果把函数的指针(地址)作为参数传递给另⼀个函数,当这个指针被⽤来调⽤其所指向的函数时,被调⽤的函数就是回调函数。
#include
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 menu()
{
printf(
"****************************\n"
"********请选择:>************\n"
"*****1.Add 2.Sub**********\n"
"*****3.Mul 4.Div**********\n"
"****************************\n");
}
int calcu(int (*pf)(int, int))
{
int ret = 0, x = 0, y = 0;
scanf("%d %d", &x, &y);
ret=pf(x, y);
printf("结果是:%d\n", ret);
}
int main()
{
int x = 0, y = 0, choice = 0;
do
{
menu();
printf("请选择:\n");
scanf("%d", &choice);
printf("请输入操作数:\n");
switch (choice)
{
case 0:
break;
case 1:
calcu(Add);
break;
case 2:
calcu(Sub);
break;
case 3:
calcu(Mul);
break;
case 4:
calcu(Div);
break;
default:
printf("输入错误,重输!\n");
}
} while (choice);
}