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));}
原创粉丝点击