gpt4 book ai didi

c++ - 你如何传递一个成员函数指针?

转载 作者:IT老高 更新时间:2023-10-28 12:52:36 26 4
gpt4 key购买 nike

我正在尝试将类中的成员函数传递给接受成员函数类指针的函数。我遇到的问题是我不确定如何使用 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;
}

如果有人对我如何正确发送此功能有任何建议,以便我以后可以使用它。

最佳答案

要通过指针调用成员函数,需要两件事:指向对象的指针和指向函数的指针。你需要在 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;
}

关于c++ - 你如何传递一个成员函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/130322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com