Home > Backend Development > C++ > How to Pass a C Member Function Pointer to an External Function?

How to Pass a C Member Function Pointer to an External Function?

DDD
Release: 2024-11-27 05:56:13
Original
552 people have browsed it

How to Pass a C   Member Function Pointer to an External Function?

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template