在C++中实现事件(委托)(续)(二)

2014-11-24 08:18:51 · 作者: · 浏览: 1
t for the console application.
//
#include "stdafx.h"
#include
#include "event2.h"
using namespace std;
class CObjectX
{
};
class CClickEventArgs: public CObjectX
{
};
class CButton: public CObjectX
{
public:
void FireClick()
{
CClickEventArgs args;
OnClicked(this, args);
}
typedef Common::CEventHandler ButtonClickEventHandler;
Common::CEvent OnClicked;
};
class CMyClass
{
public:
int OnBtuttonClicked(CObjectX* pButton, CClickEventArgs& args)
{
cout << "CMyClass: Receive button clicked event" << endl;
return 1;
}
};
int OnBtuttonClicked_C_fun(CObjectX* pButton, CClickEventArgs& args)
{
cout << "C Style Function: Receive button clicked event" << endl;
return 1;
}
class CMyFunObj
{
public:
int operator()(CObjectX* pButton, CClickEventArgs& args)
{
cout << "Functor: Receive button clicked event" << endl;
return 1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CButton btn;
CMyClass obj;
Common::cookie_type c1 = btn.OnClicked += CButton::ButtonClickEventHandler(&obj, &CMyClass::OnBtuttonClicked);
Common::cookie_type c2 = btn.OnClicked += CButton::ButtonClickEventHandler(OnBtuttonClicked_C_fun);
CMyFunObj functor;
Common::cookie_type c3 = btn.OnClicked += CButton::ButtonClickEventHandler(functor);
btn.FireClick();
btn.OnClicked -= c2;
std::cout << endl;
btn.FireClick();
system("pause");
return 0;
}
怎么样,是不是感觉和C#一样了 !
最后,我们比较一下2种实现方式:
第一种方法把委托函数类型封装起来了,对外部来说是透明的, 使用起来更简单。
第二种方式把委托函数的类型暴露了出来, 适用于事件处理函数类型各异,比较强调事件处理函数类型的场合。