简单的示例:
#include <iostream> using namespace std; int sum(int x, int y) { return x + y; } int main() { cout << sum(1, 2) << endl; int (*pf)(int, int); // 未初始化 pf = sum; cout << pf(3, 4) << endl; /* output: 3 7 */ return 0; }
遇到重载的情况,编译器通过指针类型精确匹配函数。
#include <iostream> using namespace std; int sum(int x, int y) { return x + y; } int sum(int x, double y) { cout << "sum2" << endl; return x + y; } int main() { cout << sum(1, 2) << endl; int (*pf)(int, int); // 未初始化 pf = sum; cout << pf(3, 4) << endl; /* output: 3 7 */ return 0; }
将函数作为参数:
#include <iostream> using namespace std; int sum(int x, int y) { return x + y; } typedef decltype(sum) func; int useInt2(int x, int y, func f) { return f(x, y); } int main() { cout << useInt2(3, 4, sum) << endl; /* output = 7 */ return 0; }
返回类型不会自动地转换成指针,我们必须显示地将返回类型指定为指针,但是我想,除非是函数内部还可以构造函数(例如Python那样),否则返回函数也没什么用。
练习
6.54
#include <iostream> #include <vector> using namespace std; int sum(int x, int y) { return x + y; } int main() { using pf = int(*)(int, int); vector<pf> pfvec; return 0; }
6.55 & 6.56
#include <iostream> #include <vector> using namespace std; int add(int x, int y) { return x + y; } int subtract(int x, int y) { return x - y; } int multiply(int x, int y) { return x * y; } int divide(int x, int y) { return x / y; } int main() { using pf = int(*)(int, int); vector<pf> pfvec; pfvec.push_back(add); pfvec.push_back(subtract); pfvec.push_back(multiply); pfvec.push_back(divide); for (pf f : pfvec) { cout << f(12 , 4) << endl; } return 0; }
输出结果:
16 8 48 3