您的位置:首页 > 其它

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

2013-03-13 13:46 363 查看
//头文件
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: