【自学C++】函数指针

158 阅读1分钟

申明:本系列文章系自学笔记,方便自己记忆回顾,如有不当,欢迎指正。

C++ 中的函数指针类似java中的回调

本篇知识点:

  1. 函数指针申明
  2. 函数指针类型定义
  3. 函数指针作为参数传递
  4. lambda表达式捕获及赋值给函数指针
#include <iostream>
#include <set>
#include <vector>

using namespace std;

//函数指针作为参数
int doMethod(int (*method)(const int &a, const int &b), int &a, int &b) {
    return method(a, b);
}

//函数指针申明,funPtr相当于变量,可以直接赋值
int (*funPtr)(const int &a, const int &b);

//指针函数类型定义,FunPtr是类型,不可以赋值,可以定义变量
typedef int (*FunPtr)(const int &a, const int &b);

int main() {
    //lambda表达式捕获
    //带捕获的lambda等价于对象
    auto sumFun = [](const int &a, const int &b) -> int {
        return a + b;
    };

    //函数指针赋值
    funPtr = [](const int &a, const int &b) -> int {
        return a + b;
    };

    //函数指针类型实例化
    FunPtr sumPtr = [](const int &a, const int &b) -> int {
        return a + b;
    };

//    //捕获的lambda可以赋值给函数指针
//    funPtr = sumFun;
//    sumPtr = sumFun;

    int param1 = 1;
    int param2 = 3;

    //直接调用
    int res = sumFun(param1, param1);
    int res1 = funPtr(param1, param1);
    int res2 = sumPtr(param1, param1);

    //引用调用
    int res3 = doMethod(sumFun, param1, param2);
    int res4 = doMethod(funPtr, param1, param2);
    int res5 = doMethod(sumPtr, param1, param2);

    cout << res << endl;
    cout << res1 << endl;
    cout << res2 << endl;

    cout << res3 << endl;
    cout << res4 << endl;
    cout << res5 << endl;

    return 0;
}

输出结果: 2 2 2 4 4 4

Process finished with exit code 0