coco2d-x中成员函数回调实现原理

//头文件
#ifndef __COOCS2D_CALLBACK_H__  
#define __COOCS2D_CALLBACK_H__  

#include <iostream>  
#include <string>  

using namespace std;  

// 基类  
class Person {  

public:  
	void name(string name);  
};  

// 定义基类的成员函数指针  
typedef void (Person::*SEL_CallFun)(string str);  

#define callFunc_selector(_SELECTOR) (SEL_CallFun)(&_SELECTOR)

// 派生类  
class Student : public Person{  
private:  
	string m_name;  
	int m_age;  

public:  
	Student(string name, int age);  
	~Student();  

	// 回调  
	void callBack(string str);  

	// say方法,要调用回调函数。  
	void say();  
protected:  
	// 回调的执行者  
	Person *m_pListen;  

	// 回调函数指针  
	SEL_CallFun m_pfnSelectior;  
};  
#endif



//cpp文件

#include "cocos2dx_callback.h"

void Person::name(string name)  
{  
	cout<<name<<endl;  
}  

Student::Student(string name, int age)  
{  
	this->m_name = name;  
	this->m_age = age;  
}  

Student::~Student()  
{  

}  

void Student::say()  
{  
	cout<<"Hi this is a Student"<<endl;  

	// 回调函数指针赋值。需要强转成 SEL_CallFun  
	//m_pfnSelectior = (SEL_CallFun)(&Student::callBack);  
	m_pfnSelectior = callFunc_selector(Student::callBack);

	// 回调的执行对象,传this  
	m_pListen = this;  

	// 调用回调,参数是个string  
	(m_pListen->*m_pfnSelectior)(m_name);  
}  

// 成员函数,要回调的函数  
void Student::callBack(string str)  
{  
	cout<<"My name is "  
		<< str<<endl  
		<< "age is "  
		<<m_age<<endl;  
}  

//main函数

#include <iostream>  
#include "cocos2dx_callback.h"

int main(int argc, const char * argv[])  
{  

	Student *a = new Student("Join",20);  
	a->say(); 
	system("pause");
	return 0;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值