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

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

你如何傳遞成員函數指針?

你如何傳遞成員函數指針?

C++
尚方寶劍之說 2019-08-19 16:48:05
你如何傳遞成員函數指針?我試圖將類中的成員函數傳遞給一個帶有成員函數類指針的函數。我遇到的問題是我不確定如何使用this指針在類中正確執行此操作。有沒有人有建議?這是傳遞成員函數的類的副本:class testMenu : public MenuScreen{public:bool draw;MenuButton<testMenu> x;testMenu():MenuScreen("testMenu"){     x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&this->test2);     draw = false;}void test2(){     draw = true;}};函數x.SetButton(...)包含在另一個類中,其中“object”是模板。void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) {     BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);     this->ButtonFunc = &ButtonFunc;}如果有人對如何正確發送此功能有任何建議,以便我以后可以使用它。
查看完整描述

3 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

要通過指針調用成員函數,您需要兩件事:指向對象的指針和指向函數的指針。你需要兩個MenuButton::SetButton()

template <class object>void MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath,
        LPCWSTR hoverFilePath, LPCWSTR pressedFilePath,
        int Width, int Height, object *ButtonObj, void (object::*ButtonFunc)()){
  BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);

  this->ButtonObj = ButtonObj;
  this->ButtonFunc = ButtonFunc;}

然后你可以使用兩個指針來調用函數:

((ButtonObj)->*(ButtonFunc))();

不要忘記將指針傳遞給您的對象MenuButton::SetButton()

testMenu::testMenu()
  :MenuScreen("testMenu"){
  x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"),
        TEXT("buttonPressed.png"), 100, 40, this, test2);
  draw = false;}


查看完整回答
反對 回復 2019-08-19
?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

我知道這是一個相當古老的話題。但是有一種優雅的方法可以用c ++ 11來處理這個問題

#include <functional>

像這樣聲明你的函數指針

typedef std::function<int(int,int) > Max;

聲明你將這個東西傳遞給你的函數

void SetHandler(Max Handler);

假設您將正常函數傳遞給它,您可以像平常一樣使用它

SetHandler(&some function);

假設你有一個成員函數

class test{public:
  int GetMax(int a, int b);...}

在您的代碼中,您可以std::placeholders像這樣使用它

test t;Max Handler = std::bind(&test::GetMax,&t,std::placeholders::_1,std::placeholders::_2);some object.SetHandler(Handler);


查看完整回答
反對 回復 2019-08-19
  • 3 回答
  • 0 關注
  • 794 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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