回调到非静态C ++成员函数

时间:2012-04-08 03:43:32

标签: c++ function pointers callback

我希望有人能够解释这段代码,这让我很困惑。

   //-------------------------------------------------------------------------------
   // 3.5 Example B: Callback to member function using a global variable
   // Task: The function 'DoItB' does something that implies a callback to
   //       the member function 'Display'. Therefore the wrapper-function
   //       'Wrapper_To_Call_Display is used.

   #include <iostream.h>   // due to:   cout

   void* pt2Object;        // global variable which points to an arbitrary object

   class TClassB
   {
   public:

      void Display(const char* text) { cout << text << endl; };
      static void Wrapper_To_Call_Display(char* text);

      /* more of TClassB */
   };


   // static wrapper-function to be able to callback the member function Display()
   void TClassB::Wrapper_To_Call_Display(char* string)
   {
       // explicitly cast global variable <pt2Object> to a pointer to TClassB
       // warning: <pt2Object> MUST point to an appropriate object!
       TClassB* mySelf = (TClassB*) pt2Object;

       // call member
       mySelf->Display(string);
   }


   // function does something that implies a callback
   // note: of course this function can also be a member function
   void DoItB(void (*pt2Function)(char* text))
   {
      /* do something */

      pt2Function("hi, i'm calling back using a global ;-)");   // make callback
   }


   // execute example code
   void Callback_Using_Global()
   {
      // 1. instantiate object of TClassB
      TClassB objB;


      // 2. assign global variable which is used in the static wrapper function
      // important: never forget to do this!!
      pt2Object = (void*) &objB;


      // 3. call 'DoItB' for <objB>
      DoItB(TClassB::Wrapper_To_Call_Display);
   }

问题1:关于此函数调用:

DoItB(TClassB::Wrapper_To_Call_Display)

为什么Wrapper_To_Call_Display不接受任何参数,尽管它应该根据声明采用char*参数?

问题2: DoItB被声明为

void DoItB(void (*pt2Function)(char* text))

到目前为止我所理解的是DoItB将函数指针作为参数,但为什么函数调用DoItB(TClassB::Wrapper_To_Call_Display)TClassB::Wrapper_To_Call_Display作为参数,即使它不是指针也很难?

提前完成

代码段来源:http://www.newty.de/fpt/callback.html

1 个答案:

答案 0 :(得分:3)

在C / C ++中,当函数名使用没有参数时 - 也就是没有括号 - 它是一个指向函数的指针。因此TClassB::Wrapper_To_Call_Display是指向内存中地址的指针,其中实现了函数的代码。

由于TClassB::Wrapper_To_Call_Displayvoid函数的指针,只需char* void (*)(char* test),所以它的时间为DoItB,因此它与{{1}}所需的类型相匹配。