【问题标题】:Callback to a non-static C++ Member Function回调非静态 C++ 成员函数
【发布时间】:2012-04-08 03:43:31
【问题描述】:

我希望有人能解释一下这段代码 sn-p,这让我很困惑。

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

问题一:关于这个函数调用:

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作为参数甚至很难它不是一个指针?

提前感谢

sn-p代码来源:http://www.newty.de/fpt/callback.html

【问题讨论】:

    标签: c++ function pointers callback


    【解决方案1】:

    在 C/C++ 中,当使用不带参数的函数名(即没有括号)时,它是指向函数的指针。所以TClassB::Wrapper_To_Call_Display是一个指向函数代码实现的内存地址的指针。

    由于TClassB::Wrapper_To_Call_Display 是一个指向void 函数的指针,该函数采用单个char*,所以该时间是void (*)(char* test),因此它与DoItB 所需的类型匹配。

    【讨论】:

      猜你喜欢
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      相关资源
      最近更新 更多