C++实现C#的事件委托功能

C++实现C#的事件委托功能

程序代码链接:https://download.csdn.net/download/hshqing/11652704

对于添加函数指针,则可以声明函数指针类型作为参数,定义全局函数,或者静态函数,可以作为委托,如:

//静态函数
class ClaseA
{
public:
	static int test(int a)
	{
		printf("ClaseA test %d.\r\n", a);
		return a;
	}
};

//全局函数
int test(int b)
{
	printf("global fun test %d.\r\n", b);
	return 0;
}

//定义一个函数指针类型
typedef int(*MyTypeFunc)(int event_id);

class Receiver
{
public:
	void AddFunList(MyTypeFunc fun)
	{
		if (fun)
			m_FunList.push_back(fun);
	}

	void OnFun(int event_id)
	{
		std::list<MyTypeFunc>::iterator it = m_FunList.begin();
		while (it != m_FunList.end())
		{
			MyTypeFunc fun = *it;
			if (fun)
			{
				fun(event_id);
			}
			++it;
		}
	}

private:
	std::list<MyTypeFunc> m_FunList;
};

int main()
{
	Receiver receiver;
    receiver.AddFunList(&ClaseA::test);
	receiver.AddFunList(test);

	receiver.OnFun(567);

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hshqing/article/details/100511548