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; }
相关文章推荐
- Windows下利用thunk实现回调成员函数(1)
- C#中使用托管C++类,委托调用,以供托管C++类的成员函数回调的实现方式
- 简单的C++委托 —— 用模板类实现类成员函数的回调
- 实现不需要辅助函数实现回调非静态类成员函数
- 实现类成员函数回调
- 实现不需要辅助函数实现回调非静态类成员函数
- java函数回调实现原理
- 如何在类中实现回调成员函数
- 简单的C++委托 —— 用模板类实现类成员函数的回调
- 如何在类中实现回调成员函数
- 利用一组宏定义实现类成员函数的回调
- C++学习总结_成员函数的声明和实现需要注意问题
- Item 45: 利用成员函数模板接受所有兼容类型(智能指针的部分实现)
- dojo——AMD(二、AMD中class内部成员函数相互调用实现)
- 关于函数strtok和strtok_r的使用要点和实现原理
- 什么是回调函数,如何定义和实现一个类的成员函数为回调函数(转)
- C语言可变参数函数实现原理
- 转载 C 函数的可变参数实现原理
- String的类定义如下,实现它的成员函数
- 编程练习- 尝试写出String类的成员函数实现