What is the method for defining a function pointer in C++?

In C++, a function pointer is defined as follows:

  1. Define a function pointer type: typedef returnType (*functionPtrType)(parameterType1, parameterType2, …);
  2. returnType is the type of the value returned by the function.
  3. The name of the function pointer type can be customized as needed.
  4. parameterType1, parameterType2, … are the types of parameters for the function.
  5. Declare a function pointer variable: functionPtrType functionNamePtr;
  6. 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.

bannerAds