c++中的函数指针

文章目录

格式
c++ 复制代码
int (*fcnPtr)(); // fcnPtr 是一个指向函数的指针,该函数参数为空,返回值为int。
int (*const fcnPtr)();

注意其中影响优先级顺序的()不能省略,否则会变为int *fcnPtr(); 表示一个函数的声明,该函数参数为空,返回值为int*

用法
赋值和调用
c++ 复制代码
#include <iostream>
using namespace std;
int goo()
{
    cout << 1 << endl;
    return 0;
}

int goo2()
{
    cout << 2 << endl;
    return 0;
}

int foo(int x)
{
    cout << x << endl;
    return 0;
}

int main()
{
    int (*fcnPtrGoo)() { &goo }; // 赋值 (&可省略,支持隐式转换)
    fcnPtrGoo(); //调用

    fcnPtrGoo = &goo2; // 赋值
    (*fcnPtrGoo)(); //调用

    int (*fcnPtrFoo)(int) = &foo;// 赋值
    fcnPtrFoo(3); //调用

    return 0;
}

注意函数指针的参数和返回值类型必须和原函数一致

c++ 复制代码
// function prototypes
int foo();
double goo();
int hoo(int x);

// function pointer initializers
int (*fcnPtr1)(){ &foo };    // okay
int (*fcnPtr2)(){ &goo };    // wrong -- return types don't match!
double (*fcnPtr4)(){ &goo }; // okay
fcnPtr1 = &hoo;              // wrong -- fcnPtr1 has no parameters, but hoo() does
int (*fcnPtr3)(int){ &hoo }; // okay
作为函数参数
c++ 复制代码
void selectionSort(int* array, int size, bool (*comparisonFcn)(int, int))

can be equivalently written as:

c++ 复制代码
void selectionSort(int* array, int size, bool comparisonFcn(int, int))
使用alias简化
  1. using

    c++ 复制代码
    using ValidateFunction = bool(*)(int, int);

    From

    c++ 复制代码
    bool validate(int x, int y, bool (*fcnPtr)(int, int)); // ugly

    To

    c++ 复制代码
    bool validate(int x, int y, ValidateFunction pfcn) // clean
  2. std::function

    c++ 复制代码
    #include <functional>
    bool validate(int x, int y, std::function<bool(int, int)> fcn); // std::function method that returns a bool and takes two int parameters
c++ 复制代码
using ValidateFunctionRaw = bool(*)(int, int); // type alias to raw function pointer
using ValidateFunction = std::function<bool(int, int)>; // type alias to std::function

简化后的赋值调用

c++ 复制代码
int main()
{
    using FcnPtrGooAlias = int(*)();
    FcnPtrGooAlias fcnGoo{ &goo };
    fcnGoo();

    std::function<int(int)> fcnFoo = &foo;
    fcnFoo(2);

    return 0;
}

Reference
https://www.learncpp.com/cpp-tutorial/function-pointers/

Foo(2);

复制代码
return 0;

}

复制代码
Reference
<https://www.learncpp.com/cpp-tutorial/function-pointers/>
相关推荐
愚润求学2 小时前
【递归、搜索与回溯】FloodFill算法(一)
c++·算法·leetcode
呆呆的小草2 小时前
Cesium距离测量、角度测量、面积测量
开发语言·前端·javascript
uyeonashi2 小时前
【QT系统相关】QT文件
开发语言·c++·qt·学习
冬天vs不冷3 小时前
Java分层开发必知:PO、BO、DTO、VO、POJO概念详解
java·开发语言
sunny-ll3 小时前
【C++】详解vector二维数组的全部操作(超细图例解析!!!)
c语言·开发语言·c++·算法·面试
猎人everest4 小时前
Django的HelloWorld程序
开发语言·python·django
嵌入式@秋刀鱼4 小时前
《第四章-筋骨淬炼》 C++修炼生涯笔记(基础篇)数组与函数
开发语言·数据结构·c++·笔记·算法·链表·visual studio code
嵌入式@秋刀鱼4 小时前
《第五章-心法进阶》 C++修炼生涯笔记(基础篇)指针与结构体⭐⭐⭐⭐⭐
c语言·开发语言·数据结构·c++·笔记·算法·visual studio code
别勉.5 小时前
Python Day50
开发语言·python
whoarethenext5 小时前
使用 C/C++的OpenCV 裁剪 MP4 视频
c语言·c++·opencv