C++回调函数-实操(二)

回调通常通过函数指针、函数对象(仿函数)、Lambda 表达式或者 std::function 来实现。

1、函数指针实现回调

这一方法实现回调比较好记,就记住把函数当作参数传给方法,在方法中调用方法。

复制代码
#include <iostream>

// 回调函数类型
typedef void (*CallbackFunction)(int);

// 使用回调函数的函数
void performCallback(int value, CallbackFunction callback) {
    // 执行某些操作
    std::cout << "Performing operation with value: " << value << std::endl;

    // 调用回调函数
    callback(value * 2);
}

// 回调函数
void callbackFunction(int value) {
    std::cout << "Callback executed with value: " << value << std::endl;
}

int main() {
    performCallback(5, callbackFunction);
    return 0;
}

2、函数对象(仿函数)实现回调

复制代码
#include <iostream>

// 仿函数类
class CallbackClass {
public:
    void operator()(int value) const {
        std::cout << "Callback executed with value: " << value << std::endl;
    }
};

// 使用回调函数对象的函数
void performCallback(int value, const CallbackClass& callback) {
    // 执行某些操作
    std::cout << "Performing operation with value: " << value << std::endl;

    // 调用回调函数对象
    callback(value * 2);
}

int main() {
    CallbackClass callbackObj;
    performCallback(5, callbackObj);
    return 0;
}

3、Lambda 表达式实现回调

复制代码
#include <iostream>

// 使用回调Lambda的函数
void performCallback(int value, const std::function<void(int)>& callback) {
    // 执行某些操作
    std::cout << "Performing operation with value: " << value << std::endl;

    // 调用回调Lambda
    callback(value * 2);
}

int main() {
    // 定义并传递Lambda作为回调
    performCallback(5, [](int value) {
        std::cout << "Callback executed with value: " << value << std::endl;
    });
    return 0;
}

推荐阅读

C++ std::tr1::function和std::tr1::bind模板类介绍,qt测试-CSDN博客

相关推荐
不想写代码的星星8 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端