你如何传递成员函数指针?

时间:2022-11-07
本文介绍了你如何传递成员函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

这篇关于你如何传递成员函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:如何使用模板将 lambda 转换为 std::function 下一条:返回类型是函数签名的一部分吗?

相关文章

最新文章