找回密码
 立即注册
首页 业界区 业界 【C++】回调函数

【C++】回调函数

涂流如 2026-1-20 14:40:14
前言

学习回调函数,回调函数是通过函数指针或对象调用的函数。
回调函数就是通过函数指针或对象调用的函数,只要能一个函数能够作为参数传入并调用,这个函数就是回调函数。
  1. #include int addCallBack(int a,int b){//回调函数        std::cout  b; }bool descending(int a, int b) { return a < b; }int main() {    int data[] = {5, 2, 8, 1, 3};        sort(data, 5, ascending);   // 升序    sort(data, 5, descending);  // 降序        return 0;}
复制代码

  • 异步处理:我不知道什么时候能算完
[code]#include #include #include // 模拟异步任务void asyncTask(std::function callback) {    std::thread([callback]() {        std::this_thread::sleep_for(std::chrono::seconds(2));        int result = 42;  // 模拟计算结果        callback(result);  // 完成后通过回调通知    }).detach();}// 回调处理结果void handleResult(int result) {    std::cout

相关推荐

您需要登录后才可以回帖 登录 | 立即注册