Home > Backend Development > C++ > body text

Analyze the principle of C++ function pointers to enhance code reuse capabilities

WBOY
Release: 2024-06-04 13:45:01
Original
835 people have browsed it

A function pointer is a pointer to a function that allows dynamic calling of functions, thereby enhancing code reusability. For example, you can create a general discount calculation function that accepts a function pointer as a parameter, and create different functions for different discount types to implement different discount calculations by passing different function pointers. In C++, the sorting strategy function pointer can be used to sort the student list according to the sorting strategy, demonstrating the application of function pointers in code reuse.

剖析 C++ 函数指针增强代码复用能力的原理

Analysis of the principle of C++ function pointer to enhance code reuse ability

Introduction to function pointer

A function pointer is a pointer to a function , allowing us to call functions dynamically. Its type is a pointer to the function's return value type (or void). For example:

typedef int (*function_ptr)(int);
Copy after login

This defines a pointer type to a function that returns type int.

Advantages of function pointers

The main advantage of using function pointers is their code reusability. By using function pointers, we can avoid writing the same code segment repeatedly.

Example: Calculating Discounts

Consider a scenario where you have a function for calculating discounts:

double calculate_discount(double price, double discount_percentage) {
  return price * (1 - discount_percentage);
}
Copy after login

Using function pointers, we can create a generic discount calculation function , which accepts a function pointer as parameter:

double apply_discount(double price, function_ptr discount_function) {
  return discount_function(price);
}
Copy after login

Now we can create different functions for different discount types and pass them to the apply_discount function:

double flat_discount_function(double price) {
  // 计算固定折扣
}

double percentage_discount_function(double price) {
  // 计算百分比折扣
}
Copy after login

This way we can implement different calculation methods for discounts by passing different function pointers.

Practical Case

The following is a C++ code example that demonstrates how to use function pointers to enhance code reusability:

#include <iostream>
#include <vector>

using namespace std;

// 学生类
class Student {
public:
  string name;
  int score;
};

// 排序策略函数指针类型
typedef bool (*sort_strategy_ptr)(const Student&, const Student&);

// 排序策略:按名称升序
bool sort_by_name_ascending(const Student& a, const Student& b) {
  return a.name < b.name;
}

// 排序策略:按分数降序
bool sort_by_score_descending(const Student& a, const Student& b) {
  return a.score > b.score;
}

// 根据排序策略函数指针对学生列表进行排序
void sort_students(vector<Student>& students, sort_strategy_ptr sort_strategy) {
  sort(students.begin(), students.end(), sort_strategy);
}

int main() {
  // 初始化学生列表
  vector<Student> students = {
    {"John", 85},
    {"Jane", 90},
    {"Peter", 75},
    {"Mary", 80}
  };

  // 按名称升序排序
  sort_students(students, sort_by_name_ascending);

  // 输出按名称排序后的列表
  for (const Student& student : students) {
    cout << student.name << " " << student.score << endl;
  }

  // 按分数降序排序
  sort_students(students, sort_by_score_descending);

  // 输出按分数排序后的列表
  for (const Student& student : students) {
    cout << student.name << " " << student.score << endl;
  }

  return 0;
}
Copy after login

In this example, we define a sorting strategy Function pointer types, with specific functions created for different collations. We then pass the sort strategy function pointer to the sort_students function to sort the list of students in the desired order. This shows how function pointers can be used to enhance code reusability.

The above is the detailed content of Analyze the principle of C++ function pointers to enhance code reuse capabilities. 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