zoukankan      html  css  js  c++  java
  • c++中的回调

    一:设置一个函数指针,在需要使用的时候调用

    #include <iostream>
    typedef void (__stdcall *DownloadCallback)(const char *pURL,bool OK);
    void DownLoadFile(const char *pURL,DownloadCallback callback)
    {
        std::cout<<"downloading..."<<pURL<<""<<std::endl;
        callback(pURL,true);
    }
    void __stdcall onDownloadFinished(const char* pURL,bool bOK)
    {
        std::cout<<"onDownloadFinished..."<<pURL<<"   status:"<<bOK<<std::endl;
    }
    int main()
    {
        DownLoadFile("http://wwww.baidu.com",onDownloadFinished);
        system("pause");
        return 0;
    }
     
    二:Sink的本质是你按照对方要求实现一个C++接口,然后把你实现的接口设置给对方,对方需要触发事件时调用该接口。上面下载文件的需求,如果用Sink实现,代码如下:
    #include<iostream>
    class IDownloadSink
    {
    public: 
        virtual void OnDownloadFinished(const char *pURL,bool bOK) = 0;
    };

    class CMyDownloader
    {
    public: 
        CMyDownloader (IDownloadSink *pSink)
            :m_pSink(pSink)
        {

        }

        void DownloadFile(const char* pURL)
        {
            std::cout<<"downloading..."<<pURL<<""<<std::endl;
            if(m_pSink!=NULL)
            {
                m_pSink->OnDownloadFinished(pURL,true);
            }
        }

    private:
        IDownloadSink *m_pSink;
    };


    class CMyFile:public IDownloadSink
    {
    public: 
        void download()
        {
            CMyDownloader downloader(this);
            downloader.DownloadFile("www.baidu.com");
        }

        virtual void OnDownloadFinished(const char *pURL,bool bOK)
        {
            std::cout<<"onDownloadFinished..."<<pURL<<"   status:"<<bOK<<std::endl;
        }
    };

    void main()
    {
        CMyFile *file = new CMyFile();
        file->download();

        system("pause");
    }
     
     
     
     
     
     
  • 相关阅读:
    懵懵懂懂的样子
    scrollTop总是为0
    论搜索引擎的重要性
    利用swiper仿iphone时间设置滚轮控件
    厉害了,new Date().getTime()
    invalid Date!iphone上支持的时间格式
    我不知道的MIME
    设置canvas元素的宽高的奇妙(jiujie)发现
    用SVN在github下下载一个文件夹到本地
    c++ md5算法实现(转)
  • 原文地址:https://www.cnblogs.com/jobs1/p/10790768.html
Copyright © 2011-2022 走看看