函数指针作为参数

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)


Whi*_*ind 7

您需要将disconnectFunc声明为函数指针,而不是void指针.您还需要将其称为函数(带括号),并且不需要"*".