c++ 函数指针相关总结
作者:流星斩月 时间:2022-09-26 04:42:33
下面随笔说明函数指针用法。
函数指针的定义:
定义形式:
存储类型 数据类型 (*函数指针名)()
含义:
函数指针指向的是程序代码存储区
函数指针的典型用途-----实现函数回调
通过函数指针调用的函数
例如将函数的指针作为参数传递给一个函数,使得在处理相似事件的时候可以灵活的使用不同的方法。
调用者不关心谁是调用者
需知道存在一个具有特定原型和限制条件的被调用函数。
获取函数指针:
函数的地址就是函数名,要将函数作为参数进行传递,必须传递函数名。
声明函数指针
声明指针时,必须指定指针指向的数据类型,同样,声明指向函数的指针时,必须指定指针指向的函数类型,这意味着声明应当指定函数的返回类型以及函数的参数列表。
例如:
double cal(int); // prototype
double (*pf)(int); // 指针pf指向的函数, 输入参数为int,返回值为double
pf = cal; // 指针赋值
如果将指针作为函数的参数传递:
void estimate(int lines, double (*pf)(int)); // 函数指针作为参数传递
函数指针举例
#include <iostream>
using namespace std;
int compute(int a, int b, int(* func)(int, int))
{
return func(a, b);
}
int max(int a, int b) //求最大值
{
return ((a > b) ? a : b);
}
int min(int a, int b) //求最小值
{
return ((a < b) ? a : b);
}
int sum(int a, int b) //求和
{
return (a + b);
}
int main(void)
{
int a, b, res;
cout << "please input integer a:";
cin >> a;
cout << "please input integer b:";
cin >> b;
res = compute(a, b, &max); //输入max也可以,max也是表示地址
res = compute(a, b, &min); //输入min也可以,min也是表示地址
res = compute(a, b, &sum); //输入sum也可以,sum也是表示地址
return 0;
}
来源:https://www.cnblogs.com/iFrank/p/14444636.html
标签:c++,函数,指针
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
深入理解C♯ 7.0中的Tuple特性
2023-10-28 09:33:14
![](https://img.aspxhome.com/file/2023/7/111297_0s.png)
Java集合框架Collections原理及用法实例
2021-12-04 18:10:20
flutter 路由跳转的实现示例
2023-08-23 14:55:26
servlet异步请求的实现
2023-07-14 17:11:38
![](https://img.aspxhome.com/file/2023/4/57724_0s.png)
Java图形用户界面设计(Swing)的介绍
2022-08-23 03:29:37
![](https://img.aspxhome.com/file/2023/4/75654_0s.jpg)
详解Java中的println输入和toString方法的重写问题
2022-12-24 05:26:33
![](https://img.aspxhome.com/file/2023/8/89568_0s.jpg)
MybatisPlus代码生成器的使用方法详解
2021-08-26 07:51:38
![](https://img.aspxhome.com/file/2023/5/125655_0s.png)
JAVA中String介绍及常见面试题小结
2021-11-19 03:38:20
Java操作MongoDB模糊查询和分页查询
2023-03-12 20:31:22
c#获取两个特定字符之间的内容并输出的方法
2021-12-02 19:47:11
C#中使用UDP通信的示例
2022-11-19 21:09:07
![](https://img.aspxhome.com/file/2023/0/106520_0s.png)
java自定义切面增强方式(关于自定义注解aop)
2022-05-30 15:16:58
Android仿iphone自定义滚动选择器
2023-06-24 12:47:59
![](https://img.aspxhome.com/file/2023/9/125359_0s.gif)
java图形界面之加法计算器
2023-08-31 02:27:43
![](https://img.aspxhome.com/file/2023/7/67457_0s.jpg)
在spring boot3中使用native image的最新方法
2022-05-18 17:43:14
![](https://img.aspxhome.com/file/2023/5/89565_0s.png)
JavaSE的三大接口:Comparator,Comparable和Cloneable详解
2021-09-01 03:14:20
![](https://img.aspxhome.com/file/2023/2/81242_0s.png)
Java执行hadoop的基本操作实例代码
2022-11-13 12:08:04
springcloud Zuul动态路由的实现
2021-10-07 06:15:40
![](https://img.aspxhome.com/file/2023/0/67140_0s.png)
Java Validation Api使用方法实例解析
2023-05-16 05:44:58
![](https://img.aspxhome.com/file/2023/7/119107_0s.png)
详谈异步log4j2中的location信息打印问题
2023-12-22 05:53:31