How to pass a function pointer as a parameter in C++?

In C++, you can pass a function pointer as an argument to another function. Here is an example:

#include <iostream>

// 定义一个函数指针类型
typedef void (*FunctionPtr)(int);

// 接受函数指针作为参数的函数
void printNumber(FunctionPtr ptr, int num) {
    ptr(num);
}

// 被传递的函数
void printSquare(int num) {
    std::cout << "Square: " << num * num << std::endl;
}

int main() {
    // 将函数指针作为参数传递给另一个函数
    printNumber(printSquare, 5);

    return 0;
}

In the example above, we first define a function pointer type FunctionPtr, which takes an int parameter and returns void. Then, we define a function printNumber that takes a function pointer as a parameter, accepting a function pointer and an int parameter, and invokes the passed function pointer. Finally, in the main function, we pass the pointer of the printSquare function as an argument to the printNumber function.

When the program is executed, it will output:

Square: 25

This proves that the function pointer was successfully passed as a parameter to another function.

bannerAds