指向函数的指针、将函数作为函数的形参

转载于:https://blog.csdn.net/weixin_42380877/article/details/80937452

指向函数的指针:

指针里面容纳的是函数代码的首地址

函数指针的定义:

定义形式:

存储类型 数据类型(*函数指针名)();//注意第一个括号,如果没有这个括号则为指针类型的函数

例子:int (*p) (int i, int j);

含义:

函数指针指向的是程序代码存储区

目的:

执行函数回调 :将指针作为函数的形参

例子:

#include <iostream>
using namespace std;
 
 
int compute(int a, int b, int(*func)(int, int)){  // 这里定义名为func的指针 作为形参
	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(){
	int a, b, res;
	cout <<"Please insert an integer a: "; cin >>a;
	cout<<"Please insert an integer b: "; cin >> b;
 
 
	res = compute(a,b, & max); //& max 代表对max函数取址
	cout<<"Max of" << a << " and " << b << " is " << res <<endl;
	res = compute(a,b, & min); //& max 代表对max函数取址
	cout<<"Min of" << a << " and " << b << " is " << res <<endl;
	res = compute(a,b, & sum); //& max 代表对max函数取址
	cout<<"Sum of" << a << " and " << b << " is " << res <<endl;
}

————————————————
版权声明:本文为CSDN博主「weixin_42380877」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42380877/article/details/80937452

发布了32 篇原创文章 · 获赞 0 · 访问量 1172

猜你喜欢

转载自blog.csdn.net/qq_44296342/article/details/104599534