c++ - 回调非静态 C++ 成员函数

标签 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

最佳答案

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

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

关于c++ - 回调非静态 C++ 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10060219/

相关文章:

c - 通过函数传递变量 C

c++ - 指向对象的指针 vector

c - 我的 returnList[0] 被重写为 @5'

function - 在闭包内调用堆上函数参数

c++ - 我在使用 glDrawRangeElements 时遇到的问题

c++ - 如何在 C++ 中轻松管理 Unicode 字符串

c++ - 如何为类 union 类编写析构函数

C函数返回连接的字符串

c++ - 使用继承类型调用基类函数

c++ - 了解取消引用的类型 - const_iterator