将类的成员函数注册为回调函数

#include <iostream>

class Object 
{

};

typedef int(Object::*SAYFUNC)(const char*);

class A : public Object
{
public:
	int say(const char* msg)
	{
		std::cout << "A say " << msg << std::endl;
		return 0;
	}
};

class B : public Object
{
public:
	int run(const char* msg)
	{
		std::cout << "B run " << name << msg << std::endl;
		return 0;
	}
	char name[64];
};


class Controller 
{
public:
	Controller(SAYFUNC fun, Object* target)
	{
		this->fun = fun;
		this->target = target;

	}
	~Controller()
	{
	}
	void dofun(const char* msg) {
		// (target->*fun)(msg);
		(target->*fun)(msg);
	}
private:
	SAYFUNC fun;
	Object* target;
};


int main(void) 
{
	A* pA = new A;
	Controller* pController1 = new Controller((SAYFUNC)&A::say, pA);
	pController1->dofun("xxx1");


	
	Controller* pController2 = new Controller((SAYFUNC)&B::run, pA /*即便是传递的pA指针任然可以调用B的成员函数,类似将A* 强制转换为了 B* */);
	pController2->dofun("xxx2");



	B* pB = new B;
	strcpy(pB->name, "Vicky");
	Controller* pController3 = new Controller((SAYFUNC)&B::run, pB);
	pController3->dofun("xxx3");

	system("pause");
	return 0;
}


 

A say xxx1
B run 妄铪xxx2
B run Vickyxxx3
请按任意键继续. . .

你可能感兴趣的:(将类的成员函数注册为回调函数)