Reputation: 1
I am trying to make a little pong game with menu. So I`ve made a Button class, that stores function which i run when button gets clicked. This is how i try to set function that have to get invoked when i press button. (setOnClickFunction)
void MenuState::initializeButtons()
{
Button* startButton = new Button({ 200.f, 200.f }, { 100.f, 100.f },
"startButton");
startButton->setOnClickFunction(startButtonOnClick);
}
void MenuState::startGameButtonOnClick()
{
std::cout << "startButton\n";
}
... and this is how my Button class looks like:
class Button : public Drawable, public Transformable
{
protected:
void (*onClick)();
public:
void isClicked(Vector2i mousePos);
void setOnClickFunction(void (*function)());
};
after that i get error:
"error C3867: 'MenuState::startGameButtonOnClick': non-standard syntax; use '&' to create a pointer to member"
//EDIT
This is the code that solved my problem: //MenuState:
void MenuState::initializeButtons()
{
Button* startButton = new Button({ 200.f, 200.f }, { 100.f, 100.f },
"startButton");
startButton->setOnClickFunction(std::bind(&MenuState::startGameButtonOnClick, this));
}
//Button class:
class Button : public Drawable, public Transformable
{
protected:
std::function<void()> onClick;
public:
void isClicked(Vector2i mousePos);
void setOnClickFunction(std::function<void()> function);
};
Upvotes: 0
Views: 773
Reputation: 1045
Just use std::function
to store your click function. There are plenty of examples here
Also, have a look at std::unique_ptr
to store your button within your MenuState
Upvotes: 1