第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

C ++中的回調(diào)函數(shù)

C ++中的回調(diào)函數(shù)

C++
不負(fù)相思意 2019-11-03 08:04:44
在C ++中,何時以及如何使用回調(diào)函數(shù)?編輯:我想看一個簡單的例子來編寫一個回調(diào)函數(shù)
查看完整描述

3 回答

?
陪伴而非守候

TA貢獻(xiàn)1757條經(jīng)驗 獲得超8個贊

還有執(zhí)行回調(diào)的C方法:函數(shù)指針


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

}

現(xiàn)在,如果您希望將類方法作為回調(diào)傳遞,則這些函數(shù)指針的聲明具有更復(fù)雜的聲明,例如:


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

}



查看完整回答
反對 回復(fù) 2019-11-04
?
白衣染霜花

TA貢獻(xiàn)1796條經(jīng)驗 獲得超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;

};

我認(rèn)為這個例子說明了一切。


std::function<> 是編寫C ++回調(diào)的“現(xiàn)代”方法。



查看完整回答
反對 回復(fù) 2019-11-04
  • 3 回答
  • 0 關(guān)注
  • 509 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號