How to use function pointers in C++?
In C++, function pointers are used to store the address of a function, which can then be used to call the function. Here are the basic steps for using function pointers in C++.
- Declare function pointer: Declare a function pointer using the same return type and parameter types as the function prototype. For example, if you want to declare a pointer to a function that returns int and takes two int parameters, you can use the following syntax:
int (*ptr)(int, int);
- Function pointer initialization: allocating the address of a function to a function pointer. Initialization can be done by directly assigning the function name to the function pointer. For example, if there is a function named “add”, you can assign its address to the “ptr” pointer.
ptr = add;
- Invoke function pointer: Using a function pointer to call a function. You can use the following syntax to invoke a function pointer:
int result = (*ptr)(2, 3); // 使用指针调用函数
Alternatively, you can use the following more concise syntax:
int result = ptr(2, 3); // 省略*运算符
Here is the complete sample code:
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
int (*ptr)(int, int); // 声明函数指针
ptr = add; // 初始化函数指针
int result = ptr(2, 3); // 调用函数指针
std::cout << "Result: " << result << std::endl;
return 0;
}
Running the above code will result in:
Result: 5
This is a simple example illustrating how to declare, initialize, and use C++ function pointers. For more advanced usage and scenarios, refer to more in-depth tutorials and documentation on C++ function pointers.