我尝试调用一个函数,它作为没有参数的函数指针传递,但我无法使它工作。C++函数指针作为参数
void *disconnectFunc;
void D::setDisconnectFunc(void (*func)){
disconnectFunc = func;
}
void D::disconnected(){
*disconnectFunc;
connected = false;
}
我尝试调用一个函数,它作为没有参数的函数指针传递,但我无法使它工作。C++函数指针作为参数
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;
}
+1使用我的首选语法去引用函数指针(偏好disconnectFunc()到(* disconnectFunc)(),即使他们都很好) – Dan 2010-04-06 03:52:39
这种便携式方式还是不推荐用于便携性? – JavaRunner 2013-07-20 19:53:59
@JavaRunner:它非常便携。 – GManNickG 2013-07-21 17:46:33
您需要将disconnectFunc声明为函数指针,而不是void指针。您还需要将其称为函数(带圆括号),并且不需要“*”。
谢谢。 最终代码: void(* disconnectFunc)(); void D :: setDisconnectFunc(void(* func)()){ disconnectFunc = func; } void D :: disconnected(){ (* disconnectFunc)(); connected = false;} – 2010-04-06 01:43:56
我敢打赌,它的工作方式也更好;) – WhirlWind 2010-04-06 01:45:29
更换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;
}
http://cdecl.org/可以帮忙。 – JRL 2010-04-06 01:45:14
@JRL的cdecl没有帮助,特别是(我试着在谷歌搜索这个问题之前cdecl)。 – 2016-02-02 15:31:04