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);
}
callback(pURL,true);
}
void __stdcall onDownloadFinished(const char* pURL,bool bOK)
{
std::cout<<"onDownloadFinished..."<<pURL<<" status:"<<bOK<<std::endl;
}
{
std::cout<<"onDownloadFinished..."<<pURL<<" status:"<<bOK<<std::endl;
}
int main()
{
DownLoadFile("http://wwww.baidu.com",onDownloadFinished);
{
DownLoadFile("http://wwww.baidu.com",onDownloadFinished);
system("pause");
return 0;
}
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");
}
{
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");
}