coco2d-x中成員函式回撥實現原理
阿新 • • 發佈:2018-12-22
//標頭檔案
#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;
}