What is the method for defining a function pointer in C++?
In C++, a function pointer is defined as follows:
- Define a function pointer type: typedef returnType (*functionPtrType)(parameterType1, parameterType2, …);
- returnType is the type of the value returned by the function.
- The name of the function pointer type can be customized as needed.
- parameterType1, parameterType2, … are the types of parameters for the function.
- Declare a function pointer variable: functionPtrType functionNamePtr;
- The variable name functionNamePtr is for a function pointer and can be customized as needed.
For example, defining a function pointer type as void(*)(int, int) represents a pointer to a function that takes two arguments of type int and returns void. You can declare a function pointer variable named add like this:
typedef void (*functionPtrType)(int, int);
functionPtrType addPtr;
void add(int a, int b) {
std::cout << a + b << std::endl;
}
int main() {
addPtr = add; // 将函数地址赋给函数指针变量
addPtr(2, 3); // 等同于调用add(2, 3)
return 0;
}
The output result is 5. In the above example, addPtr points to the add function and calls it through a function pointer.