C++实现C# delegate

1 篇文章 0 订阅

1. vector方式实现

#include <iostream>
#include <vector>
using namespace std;

int ii = 0;

//typedef void(*a1)();
template<class T>
class fun
{
private:
	vector<T> v;
public:
	fun();

	void operator +=(T fa)
	{
		v.push_back(fa);
	}
	void Run();
	
};
template <class T> fun<T>::fun()
{
	;
}
template <class T> void fun<T>::Run()
{
	for (int i = 0; i < v.size(); i++)
	{
		T a;
		a = v[i];
		a();
	}
}
void a_f()
{
	int a = 0;
}
void b_f()
{
	int b = 0;
}
int main()
{
	typedef void(*a1)();
	fun<a1> f;
	fun<a1> f2;
	f += a_f;
	f += b_f;
	f.Run();
	return 0;
}

2.链表方式实现

#include <iostream>

class Line
{
private:
	typedef void (*T)(int);
	typedef struct Node
	{
		Node* last;
		T Func;
		Node* next;
	};
	Node* node_start;
	int* Count;
public:
	Line();
	void operator +=(const T fun);
	void operator -=(const T fun);
	void Run(int d);
	~Line();
};
Line::Line()
{
	Count = new int(0);
	node_start = new Node();
	node_start->last = new Node();
	node_start->Func = nullptr;
	node_start->next = new Node();
}
Line::~Line()
{
	delete Count;
	delete node_start;
}
void Line::operator +=(T fun)
{
	Node* Next = node_start->next;
	Node* Last = new Node();
	for (int i = 0; i < *Count; i++)
	{
		Last = Next;
		Next = Next->next;
	}
	Next->last = Last;
	Next->Func = fun;
	Next->next = new Node();
	(*Count)++;
}
void Line::operator -=(T fun)
{
	Node* Last = new Node();
	Last->last = new Node();
	Last->next = new Node();
	Last = node_start->next;
	for (int i = 0; i < *Count; i++)
	{
		
		if (Last->Func == fun)
		{
			
			Last->last->next = Last->next;
			Last->next->last = Last->last;
			(*Count)--;
			break;
		}
		Last = Last->next;
	}
	delete Last;
}
void Line::Run(int d)
{
	Node* next = node_start->next;
	for (int i = 0; i < *Count; i++)
	{
		next->Func(d);
		next = next->next;
	}
}




void aaa(int a)
{
	;
}
static int dex = 0;
void bbb(int a)
{
	dex++;
}

int main()
{
	int* p;
	p = (int*)malloc(10 * sizeof(int));	//申请
	p[1] = 8;	//类似数组的赋值,访问
	p[9] = 8;
	free(p);	//释放

	Line a1;
	a1 += aaa;
	a1 += bbb;
	a1 += bbb;
	a1 += bbb;
	a1 -= bbb;
	a1 -= bbb;
	a1 -= bbb;
	a1.Run(2);
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值