【DEMO】【C/C++】最简单的一种回调函数
Published on 2022-05-26 21:45 in 分类: C/C++ with 萧海~
分类: C/C++

【DEMO】【C/C++】最简单的一种回调函数

    回调函数最简单用法

    // CallBackFunc.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
    //
    #include <iostream>
    #include <string>
    using namespace std;
    string toZeroDown(int n, void *contex) {
    cout << "toZeroDown:" << -*(int*)(contex) << endl;
    return "toZeroDown";
    }
    string toZeroUp(int n, void *contex) {
    cout << "toZeroUp:" << *(int*)(contex) << endl;
    return "toZeroUp";
    }
    typedef string(*CallBackFunc)(int n, void *contex);
    void registNumCallBack(CallBackFunc callback, void *contex)
    {
    int n = 3;
    cout << "The Option of 'callback()' is:" << callback(n, contex) << endl;
    }
    int main()
    {
    for (int i = 0; i < 10; i++)
    {
    if (i % 2) {
    registNumCallBack(toZeroDown, &i);
    }
    else
    {
    registNumCallBack(toZeroUp, &i);
    }
    }
    }

    输出:

    toZeroUp:0
    The Option of 'callback()' is:toZeroUp
    toZeroDown:-1
    The Option of 'callback()' is:toZeroDown
    toZeroUp:2
    The Option of 'callback()' is:toZeroUp
    toZeroDown:-3
    The Option of 'callback()' is:toZeroDown
    toZeroUp:4
    The Option of 'callback()' is:toZeroUp
    toZeroDown:-5
    The Option of 'callback()' is:toZeroDown
    toZeroUp:6
    The Option of 'callback()' is:toZeroUp
    toZeroDown:-7
    The Option of 'callback()' is:toZeroDown
    toZeroUp:8
    The Option of 'callback()' is:toZeroUp
    toZeroDown:-9
    The Option of 'callback()' is:toZeroDown

    原文:https://blog.csdn.net/Fuel_Ming/article/details/122950838

    posted @   萧海~  阅读(44)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · winform 绘制太阳,地球,月球 运作规律
    · AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
    · 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
    · 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
    · 上周热点回顾(3.3-3.9)
    点击右上角即可分享
    微信分享提示
    电磁波切换