函数指针typedef
基本结构
typedef 数据类型 (*类型名)(参数类型);//定义了一个函数指针类型
类型名 指针名 = 函数名;//定义了一个类型名下的指针指向函数;
如:
int sum(int a,int b){
return a + b;
}
typedef int (*operation)(int,int);//定义了一个operation型的函数指针类型
operation a = sum;//定义了一个operation类型的指针a,指向sum函数
int main(){
cout << a(2,5);//使用a来调用函数sum,实参为2和5,返回值为7
}
void test(){
cout << "test" << endl;
}
typedef void (*LP)();
LP p = test;
int main(){
p();
}
函数指针数组
基本结构
typedef 数据类型 (*类型名)(参数类型);//定义了一个函数指针类型
类型名 指针名[] = {函数名1,函数名2...};//定义了一个类型名下的指针指向函数;
程序案例
#include<iostream>
using namespace std;
void t1() { cout << "test1"; }
void t2() { cout << "test2"; }
void t3() { cout << "test3"; }
void t4() { cout << "test4"; }
void t5() { cout << "test5"; }
typedef void(*LP)();
int main() {
LP a[] = { NULL,t1,t2,t3,t4,t5 };
int x;
cin >> x;
a[x]();
return 0;
}
#include<iostream>
using namespace std;
int sum(int a, int b) { return a + b; }
int poor(int a, int b) { return a - b; }
int times(int a, int b) { return a * b; }
int devide(int a, int b) { return a / b;}
typedef int (*operation)(int, int);
int main() {
operation p[] = { times,sum,NULL,poor,NULL,devide };
int a, b;
char symbol;
cin >> a >> symbol >> b;
cout << p[symbol - 42](a, b);
return 0;
}