- 函数指针的写法:
把几个相同类型的函数地址放到一个数组中,这个数组就是函数指针的数组;
不会写函数指针的数组——可以先写出函数指针,再改写为函数指针数组;
#include<iostream>
using namespace std;
int Add(int x, int y) {
return x + y;
}
int Sub(int x, int y) {
return x - y;
}
int Mul(int x, int y) {
return x * y;
}
int Div(int x, int y) {
return x / y;
}
int main() {
//指针数组
int* arr[5];
//需要一个数组可以存放4个函数的地址——函数指针的数组
int(*pa)(int, int) = Add; //函数指针
int(*paa[4])(int, int) = { Add, Sub, Mul, Div }; //函数指针的数组 paa是数组
int i = 0;
for (int i = 0; i < 4; i++) {
cout << paa[i](2, 3) << endl;
}
system("pause");
return 0;
}
- 函数指针的用途——转移表
(a)原始程序
#include<iostream>
using namespace std;
int Add(int x, int y) {
return x + y;
}
int Sub(int x, int y) {
return x - y;
}
int Mul(int x, int y) {
return x * y;
}
int Div(int x, int y) {
return x / y;
}
int main() {
int x = 0, y = 0;
int input = 0;
do {
cout<< "***********************************" << endl;
cout << "*******1:add 2:sub**************" << endl;
cout << "*******3:mul 4:div**************" << endl;
cout << "***********请选择**********************" << endl;
cin >> input;
switch (input)
{
case 1:
cout << "请输入两位操作数:" << endl;
cin >> x >> y;
cout << Add(x, y) << endl;
break;
case 2:
cout << "请输入两位操作数:" << endl;
cin >> x >> y;
cout << Sub(x, y) << endl;
break;
case 3:
cout << "请输入两位操作数:" << endl;
cin >> x >> y;
cout << Mul(x, y) << endl;
break;
case 4:
cout << "请输入两位操作数:" << endl;
cin >> x >> y;
cout << Div(x, y) << endl;
break;
case 0:
cout << "***********退出程序**********************" << endl;
break;
default:
cout << "***********输入有误*********************" << endl;
break;
}
} while (input);
system("pause");
return 0;
}
输出结果:
(b)利用函数指针数组简化程序——将switch......case语句,修改用函数指针数组,存放多个类型相同的函数的地址;
#include<iostream>
using namespace std;
int Add(int x, int y) {
return x + y;
}
int Sub(int x, int y) {
return x - y;
}
int Mul(int x, int y) {
return x * y;
}
int Div(int x, int y) {
return x / y;
}
int main() {
//int(*p)(int, int); //先写出函数指针,再改写
int(*p[5])(int, int) = { 0,Add,Sub,Mul,Div }; //转移表 数组元素个数可以不标明,拓展
int input = 0;
int x = 0, y = 0;
do {
cout << "***********************************" << endl;
cout << "*******1:add 2:sub**************" << endl;
cout << "*******3:mul 4:div**************" << endl;
cout << "***********请选择**********************" << endl;
cin >> input;
if (1 <= input && input <= 4) {
cout << "*********请输入两位操作数:*********" << endl;
cin >> x >> y;
cout << p[input](x, y) << endl;
}
else
{
cout << "***********输入有误*********" << endl;
}
} while (input);
system("pause");
return 0;
}
输出结果: