• C++回调函数理解使用


    回调:call back,意思就是回过头来再调用
    在调用一个函数时,如果函数处理时间比较长,一时半会儿没法返回处理结果,此时调用者又不想一直等待,想去干别的事情。
    此时可以放置一个回调函数,然后就去干别的,等处理完,回过头来再调用留下的回调函数来通知调用者。
    回调函数是一个函数指针,是指定的函数调用形式。
    调用者放置回调函数的操作叫做:注册回调函数
    简单例子:

     1 #ifndef CALL_BACK_H
     2 #define CALL_BACK_H
     3 
     4 #include <iostream>
     5 #include <string>
     6 using namespace std;
     7 
     8 // 回调函数定义
     9 typedef void(*pFunc)(string);
    10 
    11 // 定义要接收的函数指针对象
    12 pFunc p = nullptr;
    13 
    14 // 使用者实现回调函数
    15 void print(string str){
    16     cout << "do work!" << endl;
    17 }
    18 
    19 // 注册回调(异步接口调用)
    20 // 主调用入口
    21 // str, 回调函数参数
    22 // callback, 回调函数指针
    23 void register_callbak(string str, pFunc callback){
    24     p = callback;
    25     // do something
    26     ...
    27     
    28     // 将来的某个时候调用回调
    29     p(str); 
    30 }
    31 
    32 
    33 void test(){
    34     register_callbak("hello world", print);
    35 }
    36 
    37 #endif // CALL_BACK_H

    回调多用于异步操作,基本知识,思路很重要,特此回顾,加深理解。
    如果注册的回调函数很多,则需要用一个map等结构来存储,进行繁琐操作后,去map找到对应的回调来调用即可。

  • 相关阅读:
    Choosing the Type at Runtime
    User-Defined Components Must Be Capitalized
    Computed property names
    Controlled Components
    Handling Event
    State
    props
    Functional and Class Components
    招聘漂亮的员工
    Spread Syntax
  • 原文地址:https://www.cnblogs.com/MakeView660/p/12486368.html
Copyright © 2020-2023  润新知