(以下代码可能无法运行只能做参考)最近需要研究一下C++回调函数,没研究懂什么原理,但是发现一些好用的方法,能够应付大部分需求代码如下: 1. 在test1中定义function函数模板TextCall 2. 在test2中赋值TextCall为[](int i){//代码};或者CC_CALLBACK_1(Test2::Test2Receive, this); 3. CC_CALLBACK_1是cocos2dx封装的std::bind 具体实现没弄懂 4. 以上方法设置完事就可以调用了,当test1中Text1Demo()方法调用的时候会触发test2中的Test2Receive()和lambda Test1.h
#include <stdio.h> class Test1{ public: std::function<void(int)> TextCall; void Text1Demo(); };Test1.cpp
#include "Test1.h" void Test1::Text1Demo(){ //回调函数调用传值 TextCall(1); }Test2.h
#include <stdio.h> class Test2{ public: void Test2Demo(); //接收 void Test2Receive(int i); };Test2.cpp
#include "Test2.h" #include "Test1.h" void Test2::Test2Demo(){ Test1 * text1 = new Test1(); //1 lambda回调函数 text1->TextCall = [](int i){ }; //2 bind 回调 text1->TextCall = CC_CALLBACK_1(Test2::Test2Receive, this);} void Test2::Test2Receive(int i){ //接收回调 }