函数指针
// 使用前声明
bool (*pf)(int); // pf是一个函数指针
pf = function; // 用函数名初始化函数指针
bool b = pf(10); // 相当于bool b = function(10);
bool b = (*pf)(10); // 等同
// 重载
bool f(int);
bool f(double);
bool (*pf)(int) = f; // 返回值和形参必须严格一致
// 作为形参
int f1(int ,int);
int f2(int(*)(int,int),int,int,int); // 带函数指针形参的函数声明
main() {
int a=10,b=20,c=30;
int (*pf)(int, int); // 声明
pf = f1; // 初始化
int result = f2(pf,a,b,c); // 实参只需要指针名pf
cout<<result<<endl; // 10+20+30=60
}
int f1(int a, int b) {
return a+b;
}
int f2((*pf)(int a, int b), int a,int b,int c) {
return pf(a,b)+c;
}
// typedef简写函数指针
typedef int (*ABC)(int ,int); // 用ABC代替该函数指针
int f1(int ,int);
int f2(ABC,int,int,int);
main() {
int a=10,b=20,c=30;
ABC pf; // 声明
pf = f1; // 初始化
int result = f2(pf,a,b,c);
cout<<result<<endl; // 10+20+30=60
}
int f1(int a, int b) {
return a+b;
}
int f2(ABC abc, int a,int b,int c) {
return abc(a,b)+c;
}
// 几种typedef判断
void(*b[10])(void(*)()); // b是一个[10]大小的数组,里面存放指针,指针是函数指针,指向一个函数,它的返回值是void,形参是函数指针,它的返回值为void,形参为空。
typedef void(*A)(); // 先对函数指针进行typedef,变成了void(*b[10])(A);
typedef void(*B)(A); // 继续对外层函数指针typedef,变成了B b[10];
最终:B b[10];
double(*)()(*e)[9]; // e是一个指针,指向一个[9]大小的数组,数组里面元素是函数指针,返回值为double,形参为空。
typedef double(*A)(); // A(*e)[9];
typedef A[9]* B;
B e;