我尝试调用一个函数,该函数作为函数指针传递,没有参数,但我不能使它工作。
void *disconnectFunc;
void D::setDisconnectFunc(void (*func)){
disconnectFunc = func;
}
void D::disconnected(){
*disconnectFunc;
connected = false;
}
正确的方法是:
typedef void (*callback_function)(void); // type for conciseness
callback_function disconnectFunc; // variable to store function pointer type
void D::setDisconnectFunc(callback_function pFunc)
{
disconnectFunc = pFunc; // store
}
void D::disconnected()
{
disconnectFunc(); // call
connected = false;
}
用void *disconnectFunc;
替换void (*disconnectFunc)();
以声明函数指针类型变量。或者甚至更好地使用typedef
:
typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
fptr = func;
}
void D::disconnected()
{
fptr();
connected = false;
}
您需要将disconnectFunc声明为函数指针,而不是void指针。您还需要将其称为函数(带括号),并且不需要“*”。