Passing a Member Function Pointer
In object-oriented programming, member function pointers are used to refer to class methods. Passing them to external functions can be challenging.
In this case, a class, testMenu, attempts to pass a member function, test2, to another function using a member function class pointer. However, the developer is uncertain how to use the this pointer to properly send the function.
To solve this, the receiving function, SetButton, needs two parameters: a pointer to the object (ButtonObj) and a pointer to the function (ButtonFunc). This allows the external function to invoke the member function using both pointers: ((ButtonObj)->*(ButtonFunc))();.
The modified SetButton function becomes:
template <class object> void 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; }
In the testMenu class, the object pointer is passed to SetButton using the following syntax:
testMenu::testMenu() :MenuScreen("testMenu") { x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"), TEXT("buttonPressed.png"), 100, 40, this, test2); draw = false; }
By following these steps, the member function pointer test2 is successfully passed to the SetButton function, allowing the external function to invoke it as needed.
The above is the detailed content of How to Pass a C Member Function Pointer to an External Function?. For more information, please follow other related articles on the PHP Chinese website!