C ++中的回调函数

在C ++中,何时以及如何使用回调函数?


编辑:

我想看一个简单的例子来编写一个回调函数


不负相思意
浏览 486回答 3
3回答

陪伴而非守候

还有执行回调的C方法:函数指针//Define a type for the callback signature,//it is not necessary, but makes life easier//Function pointer called CallbackType that takes a float//and returns an inttypedef int (*CallbackType)(float);  void DoWork(CallbackType callback){  float variable = 0.0f;  //Do calculations  //Call the callback with the variable, and retrieve the  //result  int result = callback(variable);  //Do something with the result}int SomeCallback(float variable){  int result;  //Interpret variable  return result;}int main(int argc, char ** argv){  //Pass in SomeCallback to the DoWork  DoWork(&SomeCallback);}现在,如果您希望将类方法作为回调传递,则这些函数指针的声明具有更复杂的声明,例如://Declaration:typedef int (ClassName::*CallbackType)(float);//This method performs work using an object instancevoid DoWorkObject(CallbackType callback){  //Class instance to invoke it through  ClassName objectInstance;  //Invocation  int result = (objectInstance.*callback)(1.0f);}//This method performs work using an object pointervoid DoWorkPointer(CallbackType callback){  //Class pointer to invoke it through  ClassName * pointerInstance;  //Invocation  int result = (pointerInstance->*callback)(1.0f);}int main(int argc, char ** argv){  //Pass in SomeCallback to the DoWork  DoWorkObject(&ClassName::Method);  DoWorkPointer(&ClassName::Method);}

白衣染霜花

Scott Meyers举了一个很好的例子:class GameCharacter;int defaultHealthCalc(const GameCharacter& gc);class GameCharacter{public:&nbsp; typedef std::function<int (const GameCharacter&)> HealthCalcFunc;&nbsp; explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)&nbsp; : healthFunc(hcf)&nbsp; { }&nbsp; int healthValue() const { return healthFunc(*this); }private:&nbsp; HealthCalcFunc healthFunc;};我认为这个例子说明了一切。std::function<> 是编写C ++回调的“现代”方法。
打开App,查看更多内容
随时随地看视频慕课网APP