c++ 中的回调函数

看了 https://www.bilibili.com/video/av39240401?t=4023 以后记录了一下

//1 回调函数是一种讲双向依赖改为单向依赖的好方法

//2 常见回调函数:pthread

//3 函数指针

//4 回调函数:回调函数是一种在定义的模块不运行,交给另一个模块运行的函数
//回调函数的应用:尤其在调用的对象是一个黑盒子,通常是别的公司打包好的某个库,你编程时想要改变库里的某些默认行为,这是用回调函数是最好的

//5 回调函数的适用条件:
//模块之间互相独立,存在相互调用关系
//两个模块处在不同的层次,为了确保单向依赖(单项调用),通常在下层设置函数指针,在上层设置回调函数。

1 常见的回调函数

//常见的回调函数
#include <iostream>
#include <pthread.h>
#include <unistd.h>

//回调函数
void* cb(void *arg)
{
    std::cout<<"call back running"<<pthread_self()<<std::endl;
    return NULL;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, cb, NULL);   //将cb 做参数传进去
    pthread_join(tid, NULL);

    pthread_t tid2;
    pthread_create(&tid2, NULL, cb, NULL);
    pthread_join(tid, NULL);
}

2 函数指针

//函数指针

#include <stdio.h>

void fun1(void)
{
    printf("fun1\n");
}

void fun2(void)
{
    printf("fun2\n");
}

int main(void)
{
    void (*p)(void);//函数指针,只能指向无参无返回值的函数
    void (*p1)(int,int);//另一个函数指针,能够指向两个整型参数无返回值的函数
    char (*p2)(int);//函数指针,指向有一个整形参数,一个返回值的函数

    void *(*p3)(int *);
    //只能指向这样的函数
    //void *fun(int *a)


    //函数指针赋值,必须要格式(函数头)相同
    p = fun1;//让p这个指针指向fun1的整个函数

    //函数实际上就是一个代码块,这个代码块执行到最后会返回

    p();//函数指针的运行(简写的运行方法),实际就是它指向的函数对象的运行
    (*p)();//原始的运行方法

    p = fun2;//修改p的指向
    p();//运行p指向的对象

}

3 回调函数的应用

main.cpp:
#include <stdio.h>
#include "run.h"

int mystep_cb(int i)
{
    printf("记秒到时,i=%d\n",i);
    return 2018;
}

int main(void)
{
    cb_install(mystep_cb);

    run();

}
run.h:
#include <unistd.h>
#include <iostream>

//希望在run的循环里,每隔1秒运行一个函数,这个函数由main来指定(函数放在main.cpp里面)
//void (*step)(void)=NULL;//定义一个函数指针,在循环里运行

//void (*step)(int)=NULL;

int (*step)(int)=NULL;

//无限运行的函数,每秒ct自增1,
void run(void)
{
    int ct = 0;
    while(1)
    {
        if(step!=NULL)//有赋值才运行,否则不运行
        {
            int r = step(ct);
            std::cout<<"r = "<<r<<std::endl;
        }
        else
            std::cout<<"the pointer step is NULL"<<std::endl;
        ct++;
        sleep(1);
    }
}

void cb_install(int (*p)(int))
{
    step = p;
}
发布了39 篇原创文章 · 获赞 8 · 访问量 7946

猜你喜欢

转载自blog.csdn.net/weixin_40512640/article/details/103470752