为了一步步实现委托,同时也为了方便将目标问题拆解,我们采用先从普通函数入手,再到成员函数,逐步实现类似于C#中的委托。
首先,明确目标:
一、目标
#include <iostream>
#include "CMultiDelegate.h"
#include "CStaticDelegate.h"
void Say()
{
printf("void Say(): Hello world\n");
}
int main(int argc, char* argv[])
{
{
CMultiDelegate onclick;
onclick += newDelegate(Say);
//onclick -= newDelegate(Say);
onclick();
}
getchar();
return 0;
}
运行结果:
void Say(): Hello world
二、实现过程
定义接口:
IDelegate.h
#pragma once
#include <typeinfo>
class IDelegate
{
public:
virtual ~IDelegate() {
}
virtual bool isType(const std::type_info& _type) = 0;
virtual void invoke() = 0;
virtual bool compare(IDelegate *_delegate) const = 0;
};
其中virtual bool isType(const std::type_info& _type) = 0;是辅助virtual bool compare(IDelegate *_delegate) const进行判断是否相等的。
invoke()是实际工作的函数,这里就是去调用Say()函数。invoke()的参数和返回值与Say()函数相同。
虚析构函数是作为基类应该提供的,具体原因请看这篇博文:
#pragma once
#include "IDelegate.h"
class CStaticDelegate : public IDelegate
{
public:
typedef void(*Func)();
CStaticDelegate