C语言中如何编写回调函数的示例代码?
- 内容介绍
- 文章标签
- 相关推荐
本文共计688个文字,预计阅读时间需要3分钟。
前言:C++中使用class语法实现回调(当然,传统的C函数指针回调也是支持的)+ 例如,有人提供一个类库+ AfCopyFile,能够提供文件拷贝的功能,并且能通知用户当前的进度。+ int DoC()
前言
C++中使用class语法实现回调(当然,,旧式的C函数指针回调也是支持的)
比如,有人提供一个类库 AfCopyFile,能够提供文件拷贝的功能,而且能通知用户当前的进度。。。
int DoCopy(const char* source, const char* dst, AfCopyFileListener* listener);
用户只需要自己实现一个AfCopyFileListener对象,传给这个函数就行。。。
class MainJob : public AfCopyFileListener{ int OnCopyProgress(long long total, long long transfered){ } }
把Listener对象传过去
AfCopyFile af; af.DoCopy(source, dst, this);
回调机制的缺点:
无论是C语言的回调函数,还是C++里的Listener,都有一个共同的缺点:
它使代码逻辑变得难以阅读。。
我们应尽量避免使用回调机制,最好采用单向的函数调用。
本文共计688个文字,预计阅读时间需要3分钟。
前言:C++中使用class语法实现回调(当然,传统的C函数指针回调也是支持的)+ 例如,有人提供一个类库+ AfCopyFile,能够提供文件拷贝的功能,并且能通知用户当前的进度。+ int DoC()
前言
C++中使用class语法实现回调(当然,,旧式的C函数指针回调也是支持的)
比如,有人提供一个类库 AfCopyFile,能够提供文件拷贝的功能,而且能通知用户当前的进度。。。
int DoCopy(const char* source, const char* dst, AfCopyFileListener* listener);
用户只需要自己实现一个AfCopyFileListener对象,传给这个函数就行。。。
class MainJob : public AfCopyFileListener{ int OnCopyProgress(long long total, long long transfered){ } }
把Listener对象传过去
AfCopyFile af; af.DoCopy(source, dst, this);
回调机制的缺点:
无论是C语言的回调函数,还是C++里的Listener,都有一个共同的缺点:
它使代码逻辑变得难以阅读。。
我们应尽量避免使用回调机制,最好采用单向的函数调用。

