1.函数指针
1.1 声明
int* f(int a, int b);
1.2 示例
#include<iostream>
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a < b ? a : b; }
int (*f)(int, int); // 声明函数指针f,指向返回值类型为int,有两个参数类型都是int的函数
void main()
{
f = max; // 函数指针f指向求最大值的函数max
int c = (*f)(1, 2);
printf("The max value is %d \n", c); // 2
f = min; // 函数指针f指向求最小值的函数min
c = (*f)(1, 2);
printf("The min value is %d \n", c); // 1
return ;
}
2.typedef简化函数指针
一般我们会经常使用typedef来简化函数指针的调用。
2.1 声明
typedef 返回类型 (*函数指针类型名)(函参列表);
typedef是定义新的类型,定义这种类型为指向某种函数的指针。
2.2 示例
#include<iostream>
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a < b ? a : b; }
//int(*f)(int, int); // 声明函数指针f,指向返回值类型为int,有两个参数类型都是int的函数
typedef int(*Func)(int, int); // typedef定义新的类型Func,指向返回值类型为int,有两个参数类型都是int的函数
void main()
{
Func func = max; // 函数指针指向求最大值的函数max
int c = func(1, 2);
printf("The max value is %d \n", c); // 2
func = min; // 函数指针指向求最小值的函数min
c = func(1, 2);
printf("The min value is %d \n", c); // 1
getchar();
return;
}
3.类成员函数指针
类成员包含静态和非静态函数,静态跟对象无关。
3.1 非静态成员函数声明
typedef 返回类型 (类名::*函数指针类型名)(函参列表);
3.2 静态成员函数声明(和一般函数指针一样)
typedef 返回类型 (*函数指针类型名)(函参列表);
3.3 示例
#include<iostream>
using namespace std;
class A {
public:
int max(int a, int b) { return a > b ? a : b; }
static int min(int a, int b) { return a < b ? a : b; }
};
typedef int (A::*ClassFunc)(int, int);//类成员函数指针定义
typedef int(*StaticFunc)(int, int); //静态函数指针定义(和普通的函数指针相同)
int main()
{
/*
* 类成员函数指针
*/
ClassFunc pClassFunc = &A::max; //类成员函数必须加&符号,否则报错
//写法1
A a;
int c = (a.*pClassFunc)(3, 6);
cout << c << endl; //6
//写法2
A* pA = &a;
c = (pA->*pClassFunc)(3, 6);
cout << c << endl; //6
/*
* 静态成员函数指针
*/
StaticFunc pStaticFucn = &A::min; //可加&,可不加
c = pStaticFucn(3, 6);
cout << c << endl; //3
getchar();
return 0;
}