你如何传递一个成员函数指针? [英] How do you pass a member function pointer?

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

问题描述

我试图传递一个类中的成员函数到一个接受成员函数类指针的函数。我所遇到的问题是,我不知道如何正确地做这个在类中使用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(...)包含在另一个类中,其中object一个模板。

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 class 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;
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆