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

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

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

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


尚方宝剑之说
浏览 703回答 3
3回答

长风秋雁

要通过指针调用成员函数,您需要两件事:指向对象的指针和指向函数的指针。你需要两个MenuButton::SetButton()template&nbsp;<class&nbsp;object>void&nbsp;MenuButton::SetButton(int&nbsp;xPos,&nbsp;int&nbsp;yPos,&nbsp;LPCWSTR&nbsp;normalFilePath, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LPCWSTR&nbsp;hoverFilePath,&nbsp;LPCWSTR&nbsp;pressedFilePath, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;Width,&nbsp;int&nbsp;Height,&nbsp;object&nbsp;*ButtonObj,&nbsp;void&nbsp;(object::*ButtonFunc)()){ &nbsp;&nbsp;BUTTON::SetButton(xPos,&nbsp;yPos,&nbsp;normalFilePath,&nbsp;hoverFilePath,&nbsp;pressedFilePath,&nbsp;Width,&nbsp;Height); &nbsp;&nbsp;this->ButtonObj&nbsp;=&nbsp;ButtonObj; &nbsp;&nbsp;this->ButtonFunc&nbsp;=&nbsp;ButtonFunc;}然后你可以使用两个指针来调用函数:((ButtonObj)->*(ButtonFunc))();不要忘记将指针传递给您的对象MenuButton::SetButton():testMenu::testMenu() &nbsp;&nbsp;:MenuScreen("testMenu"){ &nbsp;&nbsp;x.SetButton(100,100,TEXT("buttonNormal.png"),&nbsp;TEXT("buttonHover.png"), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TEXT("buttonPressed.png"),&nbsp;100,&nbsp;40,&nbsp;this,&nbsp;test2); &nbsp;&nbsp;draw&nbsp;=&nbsp;false;}

元芳怎么了

我知道这是一个相当古老的话题。但是有一种优雅的方法可以用c ++ 11来处理这个问题#include&nbsp;<functional>像这样声明你的函数指针typedef&nbsp;std::function<int(int,int)&nbsp;>&nbsp;Max;声明你将这个东西传递给你的函数void&nbsp;SetHandler(Max&nbsp;Handler);假设您将正常函数传递给它,您可以像平常一样使用它SetHandler(&some&nbsp;function);假设你有一个成员函数class&nbsp;test{public: &nbsp;&nbsp;int&nbsp;GetMax(int&nbsp;a,&nbsp;int&nbsp;b);...}在您的代码中,您可以std::placeholders像这样使用它test&nbsp;t;Max&nbsp;Handler&nbsp;=&nbsp;std::bind(&test::GetMax,&t,std::placeholders::_1,std::placeholders::_2);some&nbsp;object.SetHandler(Handler);
打开App,查看更多内容
随时随地看视频慕课网APP