C++使用回调函数的两种方式

2023-12-15 19:44:10

一.函数指针

#include <iostream>

typedef void (*callback)(int ,int);
class MyTest
{
public:
    void setCallback(callback cb)
    {
        m_callback = cb;
    }
    
    void add(int a, int b)
    {
        m_callback(a, b);
    }
    
private:
    callback m_callback;
};

void onCallback(int a, int b)
{
    std::cout << "a + b = " << a + b << std::endl;
}

int main(int argc, char *argv[])
{
    MyTest test;
    test.setCallback(onCallback);
    test.add(1, 1);
    return 0;
}

二.std::bind和std::function

#include <functional>
#include <iostream>

typedef std::function<void (int ,int)> callback;
class MyTest
{
public:
    void setCallback(callback cb)
    {
        m_callback = cb;
    }

    void add(int a, int b)
    {
        m_callback(a, b

文章来源:https://blog.csdn.net/caoshangpa/article/details/135023371
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。