亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 508 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號