Home > Backend Development > C++ > How to Pass C Member Function Pointers Correctly?

How to Pass C Member Function Pointers Correctly?

Patricia Arquette
Release: 2024-12-04 04:50:13
Original
881 people have browsed it

How to Pass C   Member Function Pointers Correctly?

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template