我想用C++實現一個觀察者模式(各種),並且我想使用函數指針來這樣做,但是在嘗試投射時我不斷收到錯誤從B類函數指針到一個typedef函數指針:如何使用typedef函數指針來註冊回調
#include <map>
typedef int (*OutputEvent)(const char*, const char*, int);
class A
{
private:
int nextListenerId;
std::map<int, OutputEvent> listenerMap;
public:
A(){ nextListenerId = 0;}
~A(){}
inline int RegisterListener(OutputEvent callback)
{
nextListenerId++;
listenerMap[nextListenerId] = callback;
return nextListenerId;
}
};
class B
{
private:
int listenerId;
public:
B(const A& a)
{
OutputEvent e = &B::CallMeBack;
listenerId = a.RegisterListener(e);
}
~B(){}
int CallMeBack(const char* x, const char* y, int z)
{
return 0;
}
};
我創造了這個例子,我已經pasted it into codepad.org,但是當我編譯失敗(不編譯codepad.org也不在Visual Studio 2010):
Output:
t.cpp: In constructor 'B::B(const A&)':
Line 28: error: cannot convert 'int (B::*)(const char*, const char*, int)' to 'int (*)(const char*, const char*, int)' in initialization
compilation terminated due to -Wfatal-errors.
我不明白爲什麼它不能轉換功能n個指針。請有人幫助我嗎?
這已被問了很多次:http://stackoverflow.com/questions/4210710/cast-pointer-to-member-function-to-normal-pointer和更多。另見http://www.parashift.com/c++-faq-lite/pointers-to-members.html。 –
參見http://stackoverflow.com/questions/1151582/pthread-function-from-a-class。 –