C++ 函数指针作为参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2582161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:59:32  来源:igfitidea点击:

Function pointer as parameter

c++functionpointersfunction-pointers

提问by Roland Soós

I try to call a function which passed as function pointer with no argument, but I can't make it work.

我尝试调用一个不带参数作为函数指针传递的函数,但我无法让它工作。

void *disconnectFunc;

void D::setDisconnectFunc(void (*func)){
    disconnectFunc = func;
}

void D::disconnected(){
    *disconnectFunc;
    connected = false;
}

回答by GManNickG

The correct way to do this is:

正确的做法是:

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;
}

回答by Nikolai Fetissov

Replace void *disconnectFunc;with void (*disconnectFunc)();to declare function pointer type variable. Or even better use a typedef:

替换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;
}

回答by WhirlWind

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

您需要将 disconnectFunc 声明为函数指针,而不是 void 指针。您还需要将其作为函数调用(带括号),并且不需要“*”。