C++ 函数指针的用途详解
函数指针是一种指向函数的指针,它允许我们动态调用函数。函数指针在 C++ 中非常有用,因为它提供了函数抽象和灵活性的能力。
语法
函数指针的语法如下:
return_type (*function_ptr_name)(argument_list);
其中:
return_type
是函数的返回类型。function_ptr_name
是函数指针的名称。argument_list
是函数的参数列表。函数指针的用途
函数指针有许多用途,其中一些最常见的有:
实战案例:比较函数指针
以下代码段说明了如何使用函数指针来比较两个整数:
#include <iostream> #include <vector> #include <algorithm> using namespace std; // 比较函数 bool compare(int a, int b) { return a > b; } int main() { // 创建一个整数向量 vector<int> numbers = {1, 5, 3, 2, 4}; // 使用函数指针对向量进行排序 sort(numbers.begin(), numbers.end(), compare); // 打印排序后的向量 for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
此代码段输出:
5 4 3 2 1
该示例演示了如何使用函数指针动态改变比较逻辑,从而对 vector 进行排序。