Definition and usage of pointer to function in C++

In C++, pointers to functions allow you to pass functions as arguments to other functions, or to call different functions dynamically at runtime. To define and use a pointer to a function, you need to follow these steps:

**1. Define a pointer to a function**

To define a pointer to a function, you need to use the following syntax:

ReturnType (*pointerName)(ParameterType1, ParameterType2, ...);

in:

- `ReturnType` is the return type of the function pointed to by the pointer.
- `pointerName` is the name of the pointer.
- `ParameterType1`, `ParameterType2`, etc. are the required parameter types for the function pointed to by the pointer.

For example, to define a pointer to a function that takes two integer arguments and returns an integer:
int (*functionPtr)(int, int);

**2. Assign function address to pointer**

To assign a function address to a pointer, you need to use the function's name (without parentheses):
 

functionPtr = &functionName;

Alternatively, you can omit the `&` symbol, since the function name itself is a pointer to a function:
 

functionPtr = functionName;

**3. Use a pointer to a function to call a function**

To call a function using a pointer to a function, you need to use the following syntax:
 

(*pointerName)(arg1, arg2, ...);

For example, to call a function using the previously defined `functionPtr`:
 

int result = (*functionPtr)(3, 4);

Here's a complete example showing how to define and use a pointer to a function:

#include <iostream>

// 定义一个接受两个整数参数并返回它们之和的函数
int add(int a, int b) {
    return a + b;
}

int main() {
    // 定义指向函数的指针
    int (*functionPtr)(int, int);

    // 分配函数地址给指针
    functionPtr = add;

    // 使用指针调用函数
    int result = (*functionPtr)(3, 4);

    std::cout << "The sum is: " << result << std::endl;

    return 0;
}
```

输出:

```
The sum is: 7
```

Guess you like

Origin blog.csdn.net/weixin_43623488/article/details/130774412