Cocos2d-x3.1回调函数具体解释

Cocos2d-x3.1回调函数的定义CCRef.h声明。源代码,例如,下面的:

typedef void (Ref::*SEL_CallFunc)();
typedef void (Ref::*SEL_CallFuncN)(Node*);
typedef void (Ref::*SEL_CallFuncND)(Node*, void*);
typedef void (Ref::*SEL_CallFuncO)(Ref*);
typedef void (Ref::*SEL_MenuHandler)(Ref*);
typedef void (Ref::*SEL_SCHEDULE)(float);

#define callfunc_selector(_SELECTOR) static_cast<cocos2d::SEL_CallFunc>(&_SELECTOR)
#define callfuncN_selector(_SELECTOR) static_cast<cocos2d::SEL_CallFuncN>(&_SELECTOR)
#define callfuncND_selector(_SELECTOR) static_cast<cocos2d::SEL_CallFuncND>(&_SELECTOR)
#define callfuncO_selector(_SELECTOR) static_cast<cocos2d::SEL_CallFuncO>(&_SELECTOR)
#define menu_selector(_SELECTOR) static_cast<cocos2d::SEL_MenuHandler>(&_SELECTOR)
#define schedule_selector(_SELECTOR) static_cast<cocos2d::SEL_SCHEDULE>(&_SELECTOR)

实际上。这是函数指针的应用。

以下使用一个简单的样例来说明函数指针的使用:

typedef void (*p)(int i);
void func(int i)
{
    printf("%d
",i);
}
p = func;  p(1);
通过typedef定义了新类型p,p是一个函数指针,函数的參数有一个int值。返回void,p指针能够指向这种函数。函数名即是一个指针,所以p直接等于func,然后p(1),运行

通过这个样例能够发现。Cocos2d-x的回调函数也是这个道理。首先定义了6个函数指针类型。仅仅能指向Ref类的成员函数。然后定义一个定义宏定义,调用这些函数指针。这些宏定义是通过回调对象的CC_Callback_来回调,以下讲一个小样例。

#include <iostream>  //callBack.h
using namespace std;
//定义一个基类
class Person
{
public:
    void print(string name);//定义基类方法
};
//typedef一个函数指针类型
typedef void(Person::*SEL_CallFun)(string str );
//定义一个派生类
class Student : public Person
{
private:
    string m_name;
    int m_age;
public:
    Student(string name ,int age);
    ~Student();
    
    void callBack(string str);//定义一个回调函数
    void result();//打印结果
protected:
    Person* m_pListen;//回调函数的运行对象
    SEL_CallFun m_pfnSelectior;//回调函数指针
};

#include "CallBack.h"  //callBack.cpp
//定义一个基类
void Person::print(string name)
{
    cout << name << endl;
}

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

Student::~Student()
{
    
}

void Student::result()
{
    cout << "Hi this is a student" << endl;
    
    m_pfnSelectior = (SEL_CallFun)(&Student::callBack);//先将子类的回调函数转成函数指针
    
    m_pListen = this;//运行对象是this
    
    m_pListen->print(m_name);//首先运行父类的print函数
    
    (m_pListen->*m_pfnSelectior)(m_name);//运行回调函数,即子类的callBack函数
}

void Student::callBack(string str)
{
    cout << "My name is" << str << "age is" << m_age << endl;
}
#include <iostream> //main.cpp
#include "CallBack.h"
int main(int argc, const char * argv[])
{

    // insert code here...
    Student* s = new Student("YXK",20);
    s->result();
    return 0;
}

通过演示示例Person对象回调函数的子类




原文地址:https://www.cnblogs.com/bhlsheji/p/5045311.html