問題描述
我試圖將類中的成員函數傳遞給采用成員函數類指針的函數.我遇到的問題是我不確定如何使用 this 指針在類中正確執行此操作.有人有建議嗎?
I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions?
這是傳遞成員函數的類的副本:
Here is a copy of the class that is passing the member function:
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(...) 包含在另一個類中,其中對象"是一個模板.
The function x.SetButton(...) is contained in another class, where "object" is a template.
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;
}
如果有人對我如何正確發送此函數有任何建議,以便我以后可以使用它.
If anyone has any advice on how I can properly send this function so that I can use it later.
推薦答案
要通過指針調用成員函數,需要兩樣東西:指向對象的指針和指向函數的指針.您需要 MenuButton::SetButton()
To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in 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;
}
然后您可以使用兩個指針調用該函數:
Then you can invoke the function using both pointers:
((ButtonObj)->*(ButtonFunc))();
不要忘記將指向您的對象的指針傳遞給 MenuButton::SetButton()
:
Don't forget to pass the pointer to your object to 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;
}
這篇關于你如何傳遞成員函數指針?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!