赞
踩
此示例用于展示鸿蒙ace2.0代码中涉及的回调函数,可参照demo示例进行理解
#include<iostream> #include <functional> using CallBack = std::function<void(int32_t)>; class Event { public: Event(std::string type, int32_t id) : eventType(type), pageId(id){} std::string GetEvenType() const { return eventType; } int32_t GetPageId() const { return pageId; } void SetCallBack(const CallBack& callback) { fun = callback; } CallBack GetCallBack() const { return fun; } void Print(std::string type,int32_t id) const { std::cout << "type=" << type.c_str()<<" " << "id=" << id << std::endl; } private: std::string eventType; int32_t pageId; CallBack fun; }; class AceAsyncEvent { public: AceAsyncEvent() = default; static std::function<void(std::string,int32_t) > create(const Event& events) { return [events](std::string str, int32_t num) { events.Print(str,num); }; } }; int main() { //创建智能指针share_ptr,使其指向Event std::shared_ptr<Event> foo=std::make_shared<Event>("touch", 0); (*foo).Print("touch", 0); std::cout << foo->GetEvenType().c_str() << std::endl; std::cout << foo->GetPageId()<< std::endl; if (!foo->GetCallBack()) { std::cout << "函数为空" << std::endl; } //lambda表达式作为参数设置到SetCallBack,此时lambda为回调函数 foo->SetCallBack([&](int32_t id) { std::cout << "函数回调,id="<<id << std::endl; }); auto fun=foo->GetCallBack(); if (fun) { std::cout << "函数不为空" << std::endl; //此时执行回调函数,即执行lamda表达式 fun(32); } auto fun2 = AceAsyncEvent::create(*foo); //此处执行回调函数,即执行events.Print(str,num) fun2("click", 1); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。