函数指针的应用
函数指针的定义方式:数据类型 (*函数指针名)(形参1,形参2…)
含义:指向函数代码的存放地址。
用途:常用于函数中套用函数。利用函数指针,可以将其作为参数,传递给另外的函数,来处理类似的问题。
例题,处理关于两个整数的计算,包括加减乘除。
#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(){
int a,b;
cout <<"enter 2 numbers:";
cin>>a>>b;
cout<<"the max is:"<<compute(a,b,&max)<<endl; //求最大值,将最大值函数的存放位置传递给计算函数。
cout<<"the min is:"<<compute(a,b,&min)<<endl; //同理,将最小值函数的存放位置传递给计算函数。
cout<<"the sum is:"<<compute(a,b,&sum)<<endl;
return 0;
}