目的 看到群里有个朋友搞了好几天函数指针传递,没搞好。所以写一篇文章,旨在从cocos2dx中帮朋友们找到如何传递指针。 旧版本的函数指针传递 全局函数函数指针调用 一般在C11之前,我们一般是这样定义一个函数指针类型。 [cpp] view plaincopyprint? typede
目的
看到群里有个朋友搞了好几天函数指针传递,没搞好。所以写一篇文章,旨在从cocos2dx中帮朋友们找到如何传递指针。
旧版本的函数指针传递
全局函数函数指针调用
一般在C++11之前,我们一般是这样定义一个函数指针类型。
[cpp] view
plaincopyprint?
- typede void(*pFunc)(int,...);
什么意思呢?
[cpp] view
plaincopyprint?
- typedef void/*return type of function*/
[cpp] view
plaincopyprint?
- (*pFunc/*the pointer of function*/)
[cpp] view
plaincopyprint?
- (int,.../*the types of function parameters*/);
- typedef void/*函数返回类型*/(*pFunc/*函数指针*/)(int,.../*函数参数类型*/);
OK,那么好了,该如何调用呢?
一般来说是像下面这样的。
[cpp] view
plaincopyprint?
- typedef void(*pFunc)();
- void fA(){ };
- void fB(pFunc pf){ (*pf)(/*里面加函数参数*/) };
- void fC(){ fB(&fA);};
即为在fC中调用fB,fB的参数为fA指针。
成员函数函数指针的调用
那么成员函数如何调用呢?
只需要加一个类名修饰符即可。
示例如下:
[cpp] view
plaincopyprint?
- class C;
- typedef void(C::*pFunc)();
- void C::fA(){};
- void C::fB(pFunc pf){ (this->*pf)()};
- void C::fC(){this->fB(&C::fA);};
其实,有心的朋友应该会注意到cocos2dx 版本中的各种selector即为宏定义的函数指针的引用,定义如下:
[cpp] view
plaincopyprint?
- 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<:sel_callfunc>(&_SELECTOR)
- #define callfuncN_selector(_SELECTOR) static_cast<:sel_callfuncn>(&_SELECTOR)
- #define callfuncND_selector(_SELECTOR) static_cast<:sel_callfuncnd>(&_SELECTOR)
- #define callfuncO_selector(_SELECTOR) static_cast<:sel_callfunco>(&_SELECTOR)
- #define menu_selector(_SELECTOR) static_cast<:sel_menuhandler>(&_SELECTOR)
- #define schedule_selector(_SELECTOR) static_cast<:sel_schedule>(&_SELECTOR)
所以不懂函数指针的朋友完全可以模仿它。 相信你很快就能上手。
C++11 中std::function的应用
cocos2dx 里面std::function定义的各种回调的解析
假设我们不知道std::function如何使用,那么只有浏览cocos2dx3.X里面的源码,我们会发现有大量的callBack 是用std::function定义的。
我们在此,首先用cocos2dx里面的网络http请求的返回函数举例。
HttpRequest 的回调定义为
inline void setResponseCallback(const ccHttpRequestCallback& callback)
{
_pCallback = callback;
}
追踪ccHttpRequestCallback,可以发现ccHttpRequestCallback即为std::function定义的:
typedef std::function
使用过的同学应该知道怎么调用的,
一般都是 setResponseCallback(CC_CALLBACK_2(ClassName::jsonRequestCompleted,this));
CC_CALLBACK是什么东东,其实就是std::bind的引用宏定义。我们查看定义如下:
[cpp] view
plaincopyprint?
- #define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__)
- #define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)
- #define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)
- #define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)
很明显,CC_CALLBACK_2就是 std::bind里面传参数,第一个是引用参数表示函数,第二个是目标,第三个,第四个是占位符,后面是不定参数。
所以可以等价代换为std::bind,那么我们上面的回调可以变成
setResponseCallback(std::bind(&ClassName::jsonRequestCompleted,this,std::placeholders::_1,std::placeholders::_2));
自定义std::function的应用
通过以上分析,相信大家已经掌握了如何通过std::function传递函数,以及std::bind去调用。不过为了照顾一些基础薄弱的朋友,我还是给出一个简单的例子。
[cpp] view
plaincopyprint?
- class C;
- void C::fA(){}
- void C::fB(const std::functionvoid()> &func)
- {
- if (func)
- {
- func();
- }
- }
- void C::fC()
- {
- fB(std::bind(&c::fA,this));
- }
关于非成员函数使用std::function
非成员函数使用std::function和上面的函数指针实际上是一致的,鉴于它比较容易,就不在此赘述了,还不会的朋友可以试一下。
申明:
http://blog.csdn.net/q229827701/article/details/41479753

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
