2

誰かにこのコードスニペットに光を当ててもらいたいのですが、それは私を混乱させます。

   //-------------------------------------------------------------------------------
   // 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

4

1 に答える 1

3

C/C++ では、関数名がパラメーターなし (つまり括弧なし) で使用されている場合、それは関数へのポインターです。関数TClassB::Wrapper_To_Call_Displayのコードが実装されているメモリ内のアドレスへのポインタも同様です。

はを 1 つ取る関数TClassB::Wrapper_To_Call_Displayへのポインタであるため、が必要とする型と一致します。voidchar*void (*)(char* test)DoItB

于 2012-04-08T04:57:21.127 に答える