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

How do you pass a member function pointer?(你如何传递成员函数指针?)
本文介绍了你如何传递成员函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Returning a pointer of a local variable C++(返回局部变量 C++ 的指针)
Inline function linkage(内联函数联动)
Which is more efficient: Return a value vs. Pass by reference?(哪个更有效:返回值与通过引用传递?)
Why is std::function not equality comparable?(为什么 std::function 不具有可比性?)
C++ overload resolution(C++ 重载解析)
When to Overload the Comma Operator?(什么时候重载逗号运算符?)