1. Function Pointers
Functions are stored in the code area of memory, and they also have addresses. If we have aint test(int a)function, then its address is the function name. This is just like an array, where the array name is the starting address of the array.
1.1 Definition of Function Pointers
data_types (*func_pointer)( data_types arg1, data_types arg2, ...,data_types argn);
For example:
int (*fp)(int a); // 这里就定义了一个指向函数(这个函数参数仅仅为一个 int 类型,函数返回值是 int 类型)的指针 fp。
Example
Note:The function pointed to by a function pointer must have the same return type, the same number of parameters, and the same parameter types.
1.2 Using typedef Can Simplify the Definition of Function Pointers
Example
1.3 Function Pointers Can Also Be Passed as Arguments to Functions
Example
Executing the above code, the output is:
10
1.4 Using Function Pointers, We Can Construct an Array of Function Pointers, More Precisely an Array of Pointers to Functions
Example
2. Function Pointers Pointing to Class Member Functions
Definition:A class member function pointer is a type of pointer data type in the C++ language, used to store access information for a member function of a specified class that has a given parameter list and return type.
Basically, there are two points to note:
- 1. When assigning a function pointer, you must use&
- 2. Use.*(instance object) or->*(instance object pointer) to call the function pointed to by the class member function pointer.
Let's look at two examples below:
A) Class Member Function Pointers Pointing to Non-static Member Functions in a Class
Fornonstatic member functiontaking its address obtains the actual address of the function in memory.
Forvirtual function, its address is unknown at compile time, so for a virtual member function, taking its address can only obtain an index value.
Example
Executing the above code, the output is:
A::set(): 0x8048a38 B::print(): 0x1 B::print(): 0x5 A: 0 A: 10 A: 100 A: 1000 A: 10000
B) Class Member Function Pointers Pointing to Static Member Functions in a Class
Example
Summary
Class member function pointers and ordinary function pointers are not the same thing. The former must use.*and ->*operator to use, while the latter can use*operator (called "dereference", or "indirection").
Ordinary function pointers actually store the starting address of the function body, so they are also called "code pointers", to distinguish them from the most commonly used data pointers in C/C++.
Class member function pointers, however, are not just the starting memory address of the class member function; they also need to solve the problem of adjusting the class instance address caused by C++ multiple inheritance and virtual inheritance. Therefore, when calling a class member function pointer, a class instance object must be passed in.
Original address: https://blog.csdn.net/crayondeng/article/details/16868351