Sink的本质是利用C++的封装、继承、多态的面向对象来实现,从实现角度来说,更优于函数指针回调;
1 // cbBysink.cpp : Defines the entry point for the console application. 2 // 3 4 #include "stdafx.h" 5 #include "cbBysink.h" 6 7 /************************************************************************/ 8 /* 上层回调函数 */ 9 /************************************************************************/10 11 class CMyWork : public baseCallBack12 {13 public:14 CMyWork()15 {16 // 注册回调17 CWork::registercallback(this);18 }19 // 回调注册实现20 void CallbackFunction(int a, int b)21 {22 cout << "a = " << a << ",b = " << b << "\n" << endl;23 return;24 }25 // 触发回调26 void makefunction(int a, int b)27 {28 CWork::makecallback(a, b);29 return;30 }31 protected:32 private:33 };34 35 int main(int argc, char* argv[])36 {37 CMyWork c_mywork;38 39 // 触发的时候不需要进行动态注册40 c_mywork.makefunction(5, 6);41 42 return 0;43 }
1 #include2 #include 3 using namespace std; 4 /************************************************************************/ 5 /* 下层回调定义 */ 6 /************************************************************************/ 7 8 class baseCallBack 9 {10 public:11 virtual void CallbackFunction(int a, int b){}; // 虚函数,提供上层实现12 protected:13 private:14 };15 16 class CWork17 {18 public:19 static void registercallback(baseCallBack *pbCallback);20 static void makecallback(int a, int b);21 protected:22 private:23 static baseCallBack *m_pbCallback;24 };25 26 baseCallBack *CWork::m_pbCallback = NULL;27 28 // 提供注册函数29 void CWork::registercallback(baseCallBack *pbCallback)30 {31 if (pbCallback != NULL)32 {33 m_pbCallback = pbCallback;34 }35 }36 37 // 提供触发接口38 void CWork::makecallback(int a, int b)39 {40 m_pbCallback->CallbackFunction(a, b);41 }