2012-04-08 96 views
2

我想讓別人看看這段代碼片段,這讓我很困惑。回調到一個非靜態的C++成員函數

//------------------------------------------------------------------------------- 
    // 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作爲參數甚至強硬它不是一個指針?

Thanx提前

代碼段的來源:http://www.newty.de/fpt/callback.html

回答

3

在C/C++,當功能名稱用於不帶參數 - 即沒有括號 - 它是一個指針到一個函數。所以TClassB::Wrapper_To_Call_Display是一個指向內存中實現函數代碼的地址的指針。

由於TClassB::Wrapper_To_Call_Display是一個指針,指向void函數採用單個char*它的時間是void (*)(char* test)所以它由DoItB所需的類型相匹配。

+0

謝謝,非常有幫助的回答 – exTrace101 2012-04-09 03:06:39

相關問題