How to Pass Member Function Pointers in C
When passing a class member function to a function that accepts a member function pointer, it's essential to provide both a pointer to the object and a pointer to the function.
In the given example, the MenuButton::SetButton() function requires a function pointer with a certain signature. To pass a member function, you need to supply both the object pointer (this) and the member function pointer. This can be achieved by modifying MenuButton::SetButton() as follows:
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; }
Now, the SetButton() function takes both the object pointer and the function pointer as parameters.
In the testMenu class, the member function can be passed like this:
testMenu::testMenu() :MenuScreen("testMenu") { x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"), TEXT("buttonPressed.png"), 100, 40, this, &testMenu::test2); draw = false; }
This provides the necessary object and member function pointers to the SetButton() function, allowing it to correctly invoke the member function later.
The above is the detailed content of How to Pass C Member Function Pointers Correctly?. For more information, please follow other related articles on the PHP Chinese website!