C++_函数-指针

本文探讨了C++中的函数指针,阐述了其在减少代码冗余方面的优势。通过示例说明了如何在函数参数中声明和使用函数指针,以及如何在主函数中传递函数指针来决定特定功能的实现。
摘要由CSDN通过智能技术生成

函数指针

  • 函数指针的好处在于可以减少一部分代码
  • 函数指针在函数参数中的写法见void bulleSort函数第三个参数, **即 bool (*pfun)(int x, in y) **
  • 函数指针的使用方式见bulleSort函数if语句内,此处表示使用提前定义的bool函数
  • 函数指针的传参方式见主函数,调用bulleSort函数时,其函数内第三个参数此时决定了bulleSort函数使用哪个bool函数
#include<iostream>
using namespace std;
bool max(int x, int y) { return x > y; }
bool min(int x, int y) { return x < y; }
void bulleSort(int arr[], int len, bool(*pfun)(int x, int y))//并不能理解这个函数指针形参的写法
{
 int temp;
 for (int i = 0; i < len-1; ++i)
 {
  for (int j = 0; j < len - i - 1; ++j)
  {
   if (pfun(arr[j + 1], arr[j]))
   {
    temp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = temp;
   }
  }
 }
}
int main()
{
 int arr[10] = { 1,2,323,223,344,563,23,6572,12 };
 cout << "用来说明函数指针-从大到小排序" << endl;
 bulleSort(arr, 10, max);//传入函数指针max
 for (auto s : arr)
 {
  cout << s << "\t";
 }
 cout << endl << endl << "用来说明函数指针-从小到大排序" << endl;
 bulleSort(arr, 10, min);//传入函数指针min
 for (auto s : arr)
 {
  cout << s << "\t";
 }
 cin.get();
 return 0;
}

指针函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值