C和C++中函数指针的用法
来源:互联网 发布:linux vsftpd配置详解 编辑:程序博客网 时间:2024/05/20 17:39
在使用python时,可以直接通过函数名传入函数参数作为回调函数,而在C和C++中,这一功能被称为函数指针
函数指针的介绍
- 函数指针指向的是函数而非对象,和其他指针一样,函数指针需要指定指向的函数类型,例如定义int *p,p指针指向的就是int形常量.在函数指针的定义中,函数的类型由函数的返回值和形参类型共同决定,而与函数名称无关
函数指针的定义
1.直接定义
在C和C++中,都可以使用形如:返回值 (函数指针命名) (参数1,参数2...)
#include<stdio.h>int sum(int a,int b){ //加法 return a+b;}int multiply(int a,int b){ //乘法 return a*b;}int divide(int a,int b){ //除法 return a/b;}int count(int(*calculate)(int,int),int a,int b){ //计算函数,传入一个计算方法的函数指针,两个数值 return calculate(a,b);}int main(){ int a,b; puts("输入a"); scanf("%i",&a); puts("输入b"); scanf("%i",&b); printf("The sum of a and b is:%i\n",count(sum,a,b)); printf("The product of a and b is:%i\n",count(multiply,a,b)); printf("The discuss of a and b is:%i\n",count(divide,a,b));}
- 运行结果如下
输入a
9
输入b
3
The sum of a and b is:12
The product of a and b is:27
The discuss of a and b is:3
2.使用typedef
typedef可以用来定义类型别名,可以使用形如:typedef 返回值 函数类型自定义名称(参数1,参数2).进行此种类型别名定义后,相当于自己定义了一个类(或者在c中叫结构体),用此类直接定义函数类型
#include<stdio.h>typedef int calculate(int,int); //函数别名定义int sum(int a,int b){ //加法 return a+b;}int multiply(int a,int b){ //乘法 return a*b;}int divide(int a,int b){ //除法 return a/b;}int count(calculate cal,int a,int b){ //计算函数,传入一个计算方法的函数指针,两个数值 return (*cal)(a,b);}int main(){ int a,b; puts("输入a"); scanf("%i",&a); puts("输入b"); scanf("%i",&b); printf("The sum of a and b is:%i\n",count(sum,a,b)); printf("The product of a and b is:%i\n",count(multiply,a,b)); printf("The discuss of a and b is:%i\n",count(divide,a,b));}
阅读全文
0 0
- c语言中函数指针的用法和技巧
- C和C++中函数指针的用法
- C语言中函数指针的用法
- C中函数指针的用法
- C函数指针的用法
- C函数指针的用法
- 函数指针的用法(C++)
- [C++] C++中const修饰指针,变量, 函数参数和函数返回值的用法总结
- C&&C++中函数指针用法示例
- c++/c 函数指针用法
- 《C和指针学习笔记》之sscanf函数的用法
- C/C++函数指针和函数指针数组用法
- C语言函数型指针和指针型函数的用法和区别
- 【C/C++】函数中指针的传递
- c语言函数指针的用法
- typedef函数指针的用法(C++)
- typedef函数指针的用法(C++)
- c/c++ 函数指针的用法
- Python使用CFFI调用C动态库
- 狼羊菜过河问题深入学习分析——Java语言描述版
- CG实验2 二维几何变换
- XML文件的读取
- Eclipse中Maven项目执行Maven update project 项目JRE System Library变为1.5的解决办法
- C和C++中函数指针的用法
- 深入Java集合学习系列:HashSet的实现原理
- ???Minimum Distance in a Star Graph
- HDOJ2011
- 2017.9.25 社交网络 思考记录
- 近期博客写于简书
- 第二十一节HTML5
- 机器学习——矩阵知识复习
- 官网Nginx下载