扩展
C++11中的std::bind
// 用图片创建菜单项;成员函数-回调函数
int a = 1;
auto menuItem1 = MenuItemImage::create("CloseNormal.png","CloseSelected.png", CC_CALLBACK_1(Chapter2_4::itemClickHandler, this, a));
// 类成员函数
void Chapter2_4::itemClickHandler(Ref* pSender, int a) {
log("item click...");
log("a:%d", a);
}
// 用图片创建菜单项;直接用bind+全局函数
// 这种写法应该不会用,游戏不是面向对象开发嘛,我只是为了学习std::bind
auto menuItem2 = MenuItemImage::create("CloseNormal.png","CloseSelected.png", (std::function)std::bind(test_func_xxx,std::placeholders::_1,2));// 搞懂std::bind
menuItem2->setPosition(origin + Vec2(0,- menuItem1->getContentSize().height * 1.5));// 看原码,menuItem 是menu子节点,相对坐标,节点坐标系 ,menu默认位置中心
// 全局函数test_func_xxx,
void test_func_xxx(Ref* sender,int b) {
log("test b: %d",b);
}
// 用label创建菜单项;lambda函数
auto label1 = Label::createWithSystemFont("菜单三", "楷体", 26);
auto menuItem3 = MenuItemLabel::create(label1, [&](Ref* sender) {
log("itemClickHandler...3");
log("data-a:%d",a);
});
模拟创建菜单项
// 4-bind 仿MenuItem #include待#include #include using namespace std::placeholders; class Test{ public: Test(){} ~Test(){} }; typedef std::function ccMenuCallback; class MenuItem{ private: std::string str; ccMenuCallback _callback; public: MenuItem(std::string _s):str(_s){} MenuItem(std::string _s,const ccMenuCallback& callback):str(_s){ _callback = callback; // _callback(this); // 那个Ref* 有待学习 _callback(new Test()); } ~MenuItem(){} static MenuItem* create(std::string str,const ccMenuCallback& callback); // void actived(){ // _callback(this); // } }; MenuItem* MenuItem::create(std::string _str,const ccMenuCallback& callback){ auto item = new (std::nothrow)MenuItem(_str,callback); return item; } // 全局函数 void func1(Test* sender, int b) { std::cout << " b: " << b << std::endl; } void func2( int b) { std::cout << " b: " << b << std::endl; } class MyClass{ public: MyClass(){} ~MyClass(){} bool init(){ // 4. 类内部传回调函数 auto menuItem4 = MenuItem::create("测试",std::bind(MyClass::func3,this,_1,32)); return true; } void func3(Test* p,int b) { std::cout << " b: " << b << std::endl; } }; int main(void) { // 1.全局函数func1,回调函数不使用 sender auto menuItem1 = MenuItem::create("测试",std::bind(func1,_1,1)); // 2.全局函数func2,回调函数使用 sender auto menuItem2 = MenuItem::create("测试",std::bind(func2,2)); // 3.类外借助类 实例化的对象,传回调函数 auto obj = MyClass(); auto menuItem3 = MenuItem::create("测试",std::bind(&MyClass::func3,obj,_1, 31)); obj.init(); printf("------------end---------------n"); return 0; }
类Ref



