为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C++
尚方宝剑之说 2019-08-19 16:48:05
你如何传递成员函数指针?我试图将类中的成员函数传递给一个带有成员函数类指针的函数。我遇到的问题是我不确定如何使用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;}如果有人对如何正确发送此功能有任何建议,以便我以后可以使用它。
查看完整描述

3 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

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


查看完整回答
反对 回复 2019-08-19
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

我知道这是一个相当古老的话题。但是有一种优雅的方法可以用c ++ 11来处理这个问题

#include <functional>

像这样声明你的函数指针

typedef std::function<int(int,int) > Max;

声明你将这个东西传递给你的函数

void SetHandler(Max Handler);

假设您将正常函数传递给它,您可以像平常一样使用它

SetHandler(&some function);

假设你有一个成员函数

class test{public:
  int GetMax(int a, int b);...}

在您的代码中,您可以std::placeholders像这样使用它

test t;Max Handler = std::bind(&test::GetMax,&t,std::placeholders::_1,std::placeholders::_2);some object.SetHandler(Handler);


查看完整回答
反对 回复 2019-08-19
  • 3 回答
  • 0 关注
  • 702 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信