函数指针是存储函数地址的变量(指向函数的入口),以后可以通过该函数指针调用该函数地址。
用处:比如想要创建callback机制并且需要将函数的地址传递给另一个函数时。 当想要存储函数数组时,函数指针也很有用,例如动态调用
基础
#includevoid HelloWorld () { std::cout << "Hello World" << std::endl; } void printNum(int n) { std::cout << n << std::endl; } int main() { HelloWorld(); // print----Hello World auto fun = HelloWorld; // fun是一个函数指针 void(*fun1)() = HelloWorld; // fun1也是一个函数指针=fun fun(); // print----Hello World // 定义了一个type对应函数指针 typedef void(*SampleFunction)(int); SampleFunction F = printNum; F(10); // print----10 return 0; }
将函数用作变量
#include#include void printValue(int value) { std::cout << value << std::endl; } void printValuePower2(int value) { std::cout << value*value << std::endl; } void printVector(const std::vector & values, void(*func)(int)) { for (int val : values) { func(val); } } int main() { std::vector Test = { 1,2,3,4,5,6,7 }; // pringVector函数,就可以允许我们对于每个value进行不同的函数操作 printVector(Test, printValue); printVector(Test, printValuePower2); return 0; }



