美文网首页
C++ 11 跨不同的类实现回调函数 std::function

C++ 11 跨不同的类实现回调函数 std::function

作者: XBruce | 来源:发表于2020-08-11 16:18 被阅读0次

    使用示例:

    // 首先定义一个函数类型
    typedef std::function<void (char*, int)> ReceiveDataCallBack;
    
    class Test
    {
    public:
        void receiveData() 
        {
             //...
            onReceiveData(buf, len);
        }
        void setOnReceiveData (ReceiveDataCallBack cb) { onReceiveData= cb; }
    
    private:
        ReceiveDataCallBack onReceiveData;
    }
    
    // 在其他类内使用的方法
    Test test;
    test.setOnReceiveData ([this](char* data, int length)
    {
             //[this]由于捕获了this指针,所以,函数内可以调用此类的变量了
    });

    相关文章

      网友评论

          本文标题:C++ 11 跨不同的类实现回调函数 std::function

          本文链接:https://www.haomeiwen.com/subject/hedydktx.html