I want to do a class that stores function pointers, but when I want to store them in member variables I get this error:
invalid use of member function (did you forget the '()' ?)
¿Where is my error?
class Button {
public:
Button(PS3USB * ps3, ButtonEnum button, void (*onPress)(void) = nullptr,
void (*onRelease)(void) = nullptr) {
PS3 = ps3;
status = false;
ERROR ---> onPressFunction = onPress; <--- ERROR
ERROR ---> onReleaseFunction = onRelease; <--- ERROR
id = button;
}
void check() {
if (PS3->getButtonClick(id) && !status) {
if (onPressFunction != nullptr) {
onPressFunction();
}
status = !status;
} else if (!PS3->getButtonClick(id) && status) {
if (onReleaseFunction != nullptr) {
onReleaseFunction();
}
status = !status;
}
}
private:
bool status;
PS3USB * PS3;
ButtonEnum id;
void * onPressFunction(void);
void * onReleaseFunction(void);
};
Thanks
Function Pointer Syntaxvoid (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.
A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions.
void * onPressFunction(void);
void * onReleaseFunction(void);
These are declarations of a member functions, not a function pointer. To declare pointers to function instead use:
void (*onPressFunction)(void);
void (*onReleaseFunction)(void);
void * onPressFunction(void);
void * onReleaseFunction(void);
These above do not declare a function pointer, but they create a member function each returning a pointer to a void, I think you meant this:
void (* onPressFunction)(void);
void (* onReleaseFunction)(void);
Also, for function pointers, I would recommend you use typedefs
, or std::function
Typedef Example
typedef void(*onReleaseFunction)(void);
And it could be used like this:
onReleaseFunction func = &functionname;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With