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

来源:互联网 发布:linux 线程同步机制 编辑:程序博客网 时间:2024/05/16 18:31
//头文件
#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;  }  


原创粉丝点击