Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the use of function pointers in C++

Shulou Source: shulou.com Published: 2022-06-02 14:50:12 11月17日 Update

This article mainly shows you "what is the use of function pointers in C++". The content is simple and clear. I hope it can help you solve your doubts. Now let the editor lead you to study and learn this article "what is the use of function pointers in C++?"

1. Function pointer

As the name implies, a function pointer is a pointer to a function.

Similar to data, functions in C++ also have addresses, and the address of the function is the memory address where the machine language code of the function is stored. We can pass the address of another function as an argument to the function, thus realizing the flexible call of the function.

1.1 get the address of the function

The way to get the address of a function is very simple, as long as you use the function name (not followed by arguments and parentheses). For example, if we have a function called think, then think () calls the function to get the result, and think gets the address of the function.

If we want to pass the think function as an argument to another function, we can write:

Func (think); 1.2 declare function pointers

Declaring function pointers is similar to declaring functions. We declare that a function can be written as follows:

Double process (int)

We declare that the function pointer can be written as follows:

Double (* pt) (int)

If we replace (* pt) with the function name, this is actually a function declaration. If (* pt) is a function, then pt is naturally a pointer to the function.

1.3 function pointer passing parameters

If we are going to implement a function, one of its arguments is a function pointer, and it is written in the same way as before:

Double func (double x, double (* pt) (int))

In this declaration, its second argument is a function pointer. The function you point to takes an int argument and returns a double result.

1.4 call function

Finally, let's take a look at the part that calls the function through the pointer.

In fact, it is also very simple, because we said earlier that the effect of (* pt) is the same as the function. If we called the function through the function name before, we only need to change it to call through (* pt).

Such as:

Double process (int); double (* pt) (int); pt = process;cout

Tags: Functions pointers arrays addresses points types parameters clocked variables variables complexity content that is this is case obvious three parentheses ways articles results Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Xiaomi Linux Docker MySQL