Home > Backend Development > C++ > body text

How do function pointers work in C++?

PHPz
Release: 2024-06-04 17:37:10
Original
824 people have browsed it

In C++, a function pointer is a variable pointing to a function, which can dynamically pass or store the function as a parameter. The syntax is: type name * function name. When allocating, use the function pointer address and dereference it when calling. For example, when calculating the maximum value using a function pointer, the calculation is performed by allocating the function pointer and calling it.

函数指针在 C++ 中如何工作?

How function pointers work in C++

In C++, a function pointer is a variable that points to a function. It allows us to dynamically pass functions as parameters or store them in data structures.

Syntax

The function pointer is declared like a regular function, but the type name is followed by an asterisk (*):

typedef void (*FunctionPointer)(int);
Copy after login

Assignment

We can do it like Assign a function address to a function pointer like an ordinary pointer:

FunctionPointer fp = &myFunction;
Copy after login

Call

We can call it by dereferencing the function pointer:

fp(10);
Copy after login

Practical case

Let's consider a program that uses function pointers to calculate the maximum of two numbers:

#include <iostream>

using namespace std;

// 最大值函数
int max(int a, int b) {
  return a > b ? a : b;
}

// 函数指针比较函数
int compare(int a, int b, int (*fp)(int, int)) {
  return fp(a, b);
}

int main() {
  // 分配函数指针并调用它来计算两数的最大值
  int (*fp)(int, int) = &max;
  int result = compare(5, 10, fp);

  // 打印结果
  cout << "最大值:" << result << endl;

  return 0;
}
Copy after login

The above is the detailed content of How do function pointers work in C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!