我想讓別人看看這段代碼片段,這讓我很困惑。回調到一個非靜態的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
謝謝,非常有幫助的回答 – exTrace101 2012-04-09 03:06:39