为了账号安全,请及时绑定邮箱和手机立即绑定

C ++中的回调函数

C ++中的回调函数

C++
不负相思意 2019-11-03 08:04:44
在C ++中,何时以及如何使用回调函数?编辑:我想看一个简单的例子来编写一个回调函数
查看完整描述

3 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

还有执行回调的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 int

typedef 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 instance

void 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 pointer

void 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);

}



查看完整回答
反对 回复 2019-11-04
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

Scott Meyers举了一个很好的例子:


class GameCharacter;

int defaultHealthCalc(const GameCharacter& gc);


class GameCharacter

{

public:

  typedef std::function<int (const GameCharacter&)> HealthCalcFunc;


  explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)

  : healthFunc(hcf)

  { }


  int healthValue() const { return healthFunc(*this); }


private:

  HealthCalcFunc healthFunc;

};

我认为这个例子说明了一切。


std::function<> 是编写C ++回调的“现代”方法。



查看完整回答
反对 回复 2019-11-04
  • 3 回答
  • 0 关注
  • 485 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信