A function pointer is a variable pointing to a function, allowing functions to be called dynamically without knowing the actual function at compile time. Functions include: dynamic function calls, callback functions, event processing and strategy patterns. Practical cases include: dynamic function calling (calling a specific function through a function pointer), callback function (passing a function as a callback parameter to other functions), and event processing (calling a specific function when a specific event occurs).
A function pointer is a variable that points to a function. It stores a pointer to the function's memory address. This mechanism allows us to call functions dynamically without knowing the actual function at compile time.
The function pointer has the following functions:
Dynamic function call
// 定义函数: void Print(int num) { cout << "数字:" << num << endl; } // 定义函数指针: using PrintFunc = void (*)(int); int main() { // 指向 Print 函数的函数指针: PrintFunc printPtr = Print; // 通过函数指针调用函数: printPtr(10); // 输出:"数字:10" return 0; }
Callback function
// 定义一个接收回调函数的函数: void CallMeBack(int (*callback)(int)) { if (callback) { callback(10); } } // 定义回调函数: int Callback(int num) { cout << "Callback 接收的数字:" << num << endl; return 0; } int main() { // 将 Callback 函数作为回调参数传递: CallMeBack(Callback); return 0; }
Event handling
// 定义一个事件处理函数: void OnClick() { cout << "单击发生!" << endl; } // 定义事件处理函数指针: using EventFunc = void (*)(); int main() { // 指向 OnClick 函数的事件处理函数指针: EventFunc eventHandler = OnClick; // 模拟鼠标单击事件: eventHandler(); // 输出:"单击发生!" return 0; }
The above is the detailed content of What is the role of C++ function pointers?. For more information, please follow other related articles on the PHP Chinese website!