Rol*_*oós 52 c++ pointers function-pointers function
我尝试调用一个函数,该函数作为函数指针传递,没有参数,但我不能使它工作.
void *disconnectFunc;
void D::setDisconnectFunc(void (*func)){
disconnectFunc = func;
}
void D::disconnected(){
*disconnectFunc;
connected = false;
}
Run Code Online (Sandbox Code Playgroud)
GMa*_*ckG 78
正确的方法是:
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;
}
Run Code Online (Sandbox Code Playgroud)
Nik*_*sov 10
替换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;
}
Run Code Online (Sandbox Code Playgroud)