问题
I would like to forward a callback to a function pointer. So I declare a static (int*) m_pointer1, as well as a method void RegisterCallback1( (int*)fct)
in class1.h:
public:
int RegisterCallback1( int (*fct) );
private:
static int (*m_Callback1);
in class1.cpp:
int class1::RegisterCallback1( int (*fct) )
{
m_Callback1= fct;
}
then, I want to forward the callback to the function pointer:
void class1::Callback1()
{
(*m_Callback1)();
}
But I get a compiler error "Expression must have (pointer-to)- function type I have followed tutorial and read about function pointers and they seem to do it this way without any problems. Any ideas why?
EDIT: So, I declare (int*)(void)m_Callback1 -Visual Studio requires a void there...- Then how do I call the registerCallback function with the argument?
class1.RegisterCallBack1( ??? - class2::callback -??? );
回答1:
You haven't declared a function pointer, you've declared a normal data pointer. You are missing () at the end of the declaration.
回答2:
static int (*m_Callback1)
does not declate a function pointer, just a pointer to int: you forgot about the parameter list. You meant:
static int (*m_Callback1)();
and
int RegisterCallback1( int (*fct)() );
回答3:
You can try to limit the missing () errors pointed out by Oli and Dave by using a typedef for the callback function's signature: typedef int (*)() CallBack;
This would at least have the merit of letting you think once about the precise number of brackets rather than at every point in your code where you use such a function.
来源:https://stackoverflow.com/questions/10304531/c-calling-static-function-pointer