How to define and use function pointers in C++?

In C++, a function pointer is a pointer variable that points to a function. The basic syntax for defining a function pointer is as follows:

返回值类型 (*变量名)(参数列表)

Here is an example:

#include <iostream>

// 声明一个函数指针类型
typedef void (*FuncPointer)(int);

// 定义一个函数
void printNumber(int num) {
    std::cout << "Number: " << num << std::endl;
}

int main() {
    // 定义一个函数指针变量并初始化为指向printNumber函数
    FuncPointer ptr = printNumber;

    // 使用函数指针调用函数
    ptr(10);

    return 0;
}

In the example above, we first declared a function pointer type called FuncPointer, which points to a function that takes an int as a parameter and returns void. We then defined a printNumber function and in the main function, we defined a function pointer variable ptr and initialized it to point to the printNumber function. Finally, we called the function by using the function pointer.

It is important to note that the type of function pointer must match the type of the function being pointed to, including the parameter list and return value type. Additionally, when calling a function using a function pointer, you can either use the function name with the parameter list or directly use the function pointer variable with the parameter list.

bannerAds