C++实现C# delegate
#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.pu
·
C++实现C# delegate
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)