C++ calling static function pointer

霸气de小男生 提交于 2019-12-13 17:58:48

问题


I would like to forward a callback to a function pointer. So I declare a static (int*) m_pointer1, as well as a method void RegisterCallback1( (int*)fct)

in class1.h:

public:
   int RegisterCallback1( int (*fct) );
private:
   static int (*m_Callback1);

in class1.cpp:

int class1::RegisterCallback1( int (*fct) )
{
    m_Callback1= fct;
}

then, I want to forward the callback to the function pointer:

void class1::Callback1()
{
   (*m_Callback1)();
}

But I get a compiler error "Expression must have (pointer-to)- function type I have followed tutorial and read about function pointers and they seem to do it this way without any problems. Any ideas why?

EDIT: So, I declare (int*)(void)m_Callback1 -Visual Studio requires a void there...- Then how do I call the registerCallback function with the argument?

class1.RegisterCallBack1(  ??? - class2::callback -??? );

回答1:


You haven't declared a function pointer, you've declared a normal data pointer. You are missing () at the end of the declaration.




回答2:


static int (*m_Callback1) does not declate a function pointer, just a pointer to int: you forgot about the parameter list. You meant:

static int (*m_Callback1)();

and

int RegisterCallback1( int (*fct)() );



回答3:


You can try to limit the missing () errors pointed out by Oli and Dave by using a typedef for the callback function's signature: typedef int (*)() CallBack; This would at least have the merit of letting you think once about the precise number of brackets rather than at every point in your code where you use such a function.



来源:https://stackoverflow.com/questions/10304531/c-calling-static-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!