-
函数指针
-
回调函数
1.函数指针
(1)基本形式:
int (*pf)(int)//基本形式
(2)详解:
函数指针:本质上是指针。
“要清楚一个指针需要明白指针的四方面内容:指针的类型、指针所指向的类型、指针的值或指针所指向的内存区、指针本身所占据的内存区。”
//1.p是一个指向有一个整型参数且返回值类型为整形的函数指针
//2.(*pf)说明这是个指针
//3.后面又与()结合说明是个函数,函数内的参数是整型
//4.又与外面的int结合,说明函数指针返回值类型为整型
注!!!注意指针数组、数组指针、函数指针的区分
//指针数组
int *p[a]
//数组指针
int (*p)[a]
2.回调函数
概念:就是通过函数指针调用的函数
AI注解:当一个函数 A 被另一个函数 B 所调用,并且函数 A 又需要执行一些特定的操作,但是具体的实现细节留给函数 B 去定义的时候,就会使用到回调函数。在函数 A 中,它会预留一个位置给函数 B 提供的函数(即回调函数),然后在适当的时机调用这个函数。
3.计算器代码(核心)
#include<stdio.h>
void calc(int (*pf)(int x, int y));//指针函数的运用
//先写个菜单
void menu()
{
printf("********************\n");
printf("***1.sub 2.add****\n");
printf("***3.div 4.mul****\n");
printf("**** 0.error *****\n");
}
//分别写出加减乘除的函数
int sub(int x,int y)
{
return x - y;
}
int add(int x,int y)
{
return x + y;
}
int div(int x, int y)
{
return x / y;
}
int mul(int x, int y)
{
return x * y;
}
//回调函数、函数指针
//int (*pf)(int)
void calc(int (*pf)(int x, int y))
{
int x;
int y;
printf("请输入两个操作数:");
scanf_s("%d %d", &x, &y);
printf("%d\n", pf(x, y));
}
//主函数
int main()
{
int input;
//使用do……while语句控制循环条件
do
{
menu();
printf("请选择:");
scanf_s("%d", &input);
switch (input)
{
case 1:
calc(sub);//函数回调
break;
case 2:
calc(add);
break;
case 3:
calc(div);
break;
case 4:
calc(mul);
break;
case 0:
break;
default:
break;
}
} while (input);
return 0;
}
4554

被折叠的 条评论
为什么被折叠?



