C++作為一種語言,大多數的人都是把它默認為面向對象的支持,認為他就是C語言的替代品,一種延伸而已,而事際上,C++與C是完全不同的語言。用過C++語言的朋友都覺得C++語言的確是個好語言。
但有時由於特殊需要,不得不用C++,在C++中要想實現C#中的Thread等也是可行的,不過代碼要稍復雜:
- //delegate 0
- #define DEFINE_DELEGATE(NAME, R)\
- class NAME##Delegate\
- {\
- public:\
- virtual ~NAME##Delegate(void){ }\
- virtual R operator()(void) = 0;\
- };\
- template\
- class NAME##DelegateImpl : public NAME##Delegate\
- {\
- private:\
- typedef R (C::*F)(void);\
- C* m_class;\
- F m_fun;\
- public:\
- NAME##DelegateImpl(C* c, F f){ m_class = c; m_fun = f; }\
- virtual R operator()(void)\
- {\
- if(m_class)\
- return (m_class-*m_fun)();\
- }\
- };\
- template\
- NAME##Delegate* Make##NAME##Delegate(C* c, F f)\
- {\
- return new NAME##DelegateImpl(c, f);\
- }
- //////////////////////////////////////////////////////////////////////////
- //delegate 1
- #define DEFINE_DELEGATE(NAME, R, P1)\
- class NAME##Delegate\
- {\
- public:\
- virtual ~NAME##Delegate(void){ }\
- virtual R operator()(P1 p1) = 0;\
- };\
- template\
- class NAME##DelegateImpl : public NAME##Delegate\
- {\
- private:\
- typedef R (C::*F)(P1);\
- C* m_class;\
- F m_fun;\
- public:\
- NAME##DelegateImpl(C* c, F f){ m_class = c; m_fun = f; }\
- virtual R operator()(P1 p1)\
- {\
- if(m_class)\
- return (m_class-*m_fun)(p1);\
- }\
- };\
- template\
- NAME##Delegate* Make##NAME##Delegate(C* c, F f)\
- {\
- return new NAME##DelegateImpl(c, f);\
- }
這個例子比較簡單C++語言用來實現某個功能,client是客戶程序,要想在m_sdk做處理的時候能發送通知到client,有幾個方法可以實現。其一是發線程消息,其一是回調,但傳統的回調對面向對象的支持並不好,這就是實現delegate的出發點。 下面是一個實現: class Delegate
- DEFINE_DELEGATE(Open, void, int, string)
- class sdk
- {
- public:
- OpenDelegate* pEvent;
- sdk(): pEvent(NULL) { }
- void Open()
- {
- cout
- if(pEvent != NULL)
- (*pEvent)(100, "你好");
- }
- };
- class client
- {
- private:
- sdk m_sdk;
- public:
- client()
- {
- m_sdk.pEvent = MakeOpenDelegate(this, OnOpen2);
- }
- void Open()
- {
- m_sdk.Open();
- }
- void OnOpen()
- {
- cout
- }
- void OnOpen2(int t, string str)
- {
- cout
- }
- };