c++中的函数指针

[复制链接]
发表于 2025-12-18 01:57:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
格式

  1. int (*fcnPtr)(); // fcnPtr 是一个指向函数的指针,该函数参数为空,返回值为int。
  2. int (*const fcnPtr)();
复制代码
  留意此中影响优先级序次的()不能省略,否则会变为int *fcnPtr(); 体现一个函数的声明,该函数参数为空,返回值为int*
  用法

赋值和调用

  1. #include <iostream>
  2. using namespace std;
  3. int goo()
  4. {
  5.     cout << 1 << endl;
  6.     return 0;
  7. }
  8. int goo2()
  9. {
  10.     cout << 2 << endl;
  11.     return 0;
  12. }
  13. int foo(int x)
  14. {
  15.     cout << x << endl;
  16.     return 0;
  17. }
  18. int main()
  19. {
  20.     int (*fcnPtrGoo)() { &goo }; // 赋值 (&可省略,支持隐式转换)
  21.     fcnPtrGoo(); //调用
  22.     fcnPtrGoo = &goo2; // 赋值
  23.     (*fcnPtrGoo)(); //调用
  24.     int (*fcnPtrFoo)(int) = &foo;// 赋值
  25.     fcnPtrFoo(3); //调用
  26.     return 0;
  27. }
复制代码
  留意函数指针的参数和返回值范例必须和原函数划一
  1. // function prototypes
  2. int foo();
  3. double goo();
  4. int hoo(int x);
  5. // function pointer initializers
  6. int (*fcnPtr1)(){ &foo };    // okay
  7. int (*fcnPtr2)(){ &goo };    // wrong -- return types don't match!
  8. double (*fcnPtr4)(){ &goo }; // okay
  9. fcnPtr1 = &hoo;              // wrong -- fcnPtr1 has no parameters, but hoo() does
  10. int (*fcnPtr3)(int){ &hoo }; // okay
复制代码
作为函数参数

  1. void selectionSort(int* array, int size, bool (*comparisonFcn)(int, int))
复制代码
can be equivalently written as:
  1. void selectionSort(int* array, int size, bool comparisonFcn(int, int))
复制代码
利用alias简化


  • using
    1. using ValidateFunction = bool(*)(int, int);
    复制代码
    From
    1. bool validate(int x, int y, bool (*fcnPtr)(int, int)); // ugly
    复制代码
    To
    1. bool validate(int x, int y, ValidateFunction pfcn) // clean
    复制代码
  • std::function
    1. #include <functional>
    2. bool validate(int x, int y, std::function<bool(int, int)> fcn); // std::function method that returns a bool and takes two int parameters
    复制代码
  1. using ValidateFunctionRaw = bool(*)(int, int); // type alias to raw function pointer
  2. using ValidateFunction = std::function<bool(int, int)>; // type alias to std::function
复制代码
简化后的赋值调用
  1. int main()
  2. {
  3.     using FcnPtrGooAlias = int(*)();
  4.     FcnPtrGooAlias fcnGoo{ &goo };
  5.     fcnGoo();
  6.     std::function<int(int)> fcnFoo = &foo;
  7.     fcnFoo(2);
  8.     return 0;
  9. }
复制代码
Reference
https://www.learncpp.com/cpp-tutorial/function-pointers/
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表