C++回调函数

回调函数,百度百科给的解释是:回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

废话不多说,先上代码。

/利用回调函数实现自定义定时器
#include <iostream>
#include <time.h>

using namespace std;
void MyTimer(unsigned timeGap);
void MySetTimer(void (*functor)(unsigned timeGap), unsigned timeGap);

int main(){
    int timeGap;
    cout<<"请输入时间间隔"<<endl;
    cin>>timeGap;
    MySetTimer(MyTimer, timeGap);
    return 0;
}
void MyTimer(unsigned timeGap){
    static int i=0;
    clock_t now;
    clock_t _time = clock();
    while (true){
        now = clock();
        if ((now-_time)%(timeGap*CLOCKS_PER_SEC)==0){
            cout<<"第"<<++i<<"次触发"<<endl;
            cout<<"Hello World!"<<endl;
            _time = now;
        }
    }   
}

void MySetTimer(void (*functor)(unsigned), unsigned timeGap){
    functor(timeGap);
}



运行结果如下:
在这里插入图片描述

程序每隔1秒被触发一次,输出“Hello World!”,比较简单,唯一值得强调的是下面这部分代码中的functor,它是一个函数指针,能够接受所有返回类型为void含有一个unsigned参数的函数的地址。

void MySetTimer(void (*functor)(unsigned), unsigned timeGap)
{
	MyTimer(timeGap);
}

例如可以另外定义一个函数MyTest如下:

void MyTest(unsigned n)
{
///
}

在主函数中即可用MySetTimer(MyTest, timeGap)来调用MyTest函数。这样便可以实现调用函数和被调用函数的分离。调用者不关心谁是被调用者,也不关心被调用者内部是怎么实现的,所有它需知道的只是存在某种特定类型的函数而已。这样也相当于实现了对被调用者的封装,可以通过一个函数原型实现一系列不同的函数操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的回调函数是指将一个函数作为参数传递给另一个函数,以便在需要的时候调用该函数。回调函数通常用于事件处理或异步编程中。 以下是一个简单的回调函数示例: ```c++ #include <iostream> void printResult(int result) { std::cout << "Result: " << result << std::endl; } void calculate(int x, int y, void (*callback)(int)) { int result = x + y; callback(result); } int main() { calculate(5, 7, printResult); return 0; } ``` 在上面的示例中,`calculate()`函数接受两个整数和一个函数指针作为参数。它计算这两个整数的和,并将结果传递给回调函数。`printResult()`函数被传递给`calculate()`函数作为回调函数。当`calculate()`函数计算出结果后,它调用回调函数`printResult()`来打印结果。 此外,C++11引入了`std::function`和`std::bind`,它们可以更方便地使用回调函数。例如: ```c++ #include <iostream> #include <functional> void printResult(int result) { std::cout << "Result: " << result << std::endl; } void calculate(int x, int y, std::function<void(int)> callback) { int result = x + y; callback(result); } int main() { auto f = std::bind(printResult, std::placeholders::_1); calculate(5, 7, f); return 0; } ``` 在这个示例中,`calculate()`函数接受两个整数和一个`std::function`对象作为参数。`std::function`对象包装回调函数`printResult()`,并将其传递给`calculate()`函数。`std::bind`函数用于将回调函数绑定到要传递的参数上。最后,`f`对象被传递给`calculate()`函数作为回调函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值