你如何傳遞成員函數(shù)指針?我試圖將類中的成員函數(shù)傳遞給一個帶有成員函數(shù)類指針的函數(shù)。我遇到的問題是我不確定如何使用this指針在類中正確執(zhí)行此操作。有沒有人有建議?這是傳遞成員函數(shù)的類的副本: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;}};函數(shù)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;}如果有人對如何正確發(fā)送此功能有任何建議,以便我以后可以使用它。
3 回答

長風(fēng)秋雁
TA貢獻1757條經(jīng)驗 獲得超7個贊
要通過指針調(diào)用成員函數(shù),您需要兩件事:指向?qū)ο蟮闹羔樅椭赶蚝瘮?shù)的指針。你需要兩個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;}
然后你可以使用兩個指針來調(diào)用函數(shù):
((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;}

元芳怎么了
TA貢獻1798條經(jīng)驗 獲得超7個贊
我知道這是一個相當古老的話題。但是有一種優(yōu)雅的方法可以用c ++ 11來處理這個問題
#include <functional>
像這樣聲明你的函數(shù)指針
typedef std::function<int(int,int) > Max;
聲明你將這個東西傳遞給你的函數(shù)
void SetHandler(Max Handler);
假設(shè)您將正常函數(shù)傳遞給它,您可以像平常一樣使用它
SetHandler(&some function);
假設(shè)你有一個成員函數(shù)
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);
- 3 回答
- 0 關(guān)注
- 788 瀏覽
添加回答
舉報
0/150
提交
取消