《C++ primer》里面讲到函数指针定义并调用,做一下练习6.54-6.56,题目如下:
vector元素的类型是函数指针的类型是int (*)(int, int)
,指向的元素是有两个int形参,返回类型也是int的函数。
cpp
#include <vector>
#include <iostream>
using namespace std;
int add(int num1, int num2)
{
return num1 + num2;
}
int subtract(int num1, int num2)
{
return num1 - num2;
}
int multiply(int num1, int num2)
{
return num1 * num2;
}
int divide(int num1, int num2)
{
return num1 / num2;
}
int main()
{
vector<int (*)(int, int)> a;
a.push_back(add);
a.push_back(subtract);
a.push_back(multiply);
a.push_back(divide);
int res_add = a[0](6, 3);
int res_subtract = a[1](6, 3);
int res_multiply = a[2](6, 3);
int res_divide = a[3](6, 3);
cout << res_add << " " << res_subtract << " " << res_multiply << " " << res_divide;
return 0;
}
输出