我正在尝试使用 C++ 实现一个(某种)观察者模式,并且我想使用函数指针来实现,但是在尝试将函数指针从类 B 转换为 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.
我不明白为什么它不能转换函数指针。有人可以帮帮我吗?
最佳答案
您尝试转换为 OutputEvent
的函数是一个成员函数。这在错误消息中清楚地表示为:
'int (B::*)(const char*, const char*, int)'
与
不同的类型 int (*OutputEvent)(const char*, const char*, int)
因为 B::
部分(这意味着函数有一个不可见的 this
参数)。
如果您将成员函数定义为静态的,那么您将能够将其转换为 OutputEvent
:
class B
{
....
static int CallMeBack(const char* x, const char* y, int z);
...
};
关于c++ - 如何使用 typedef 函数指针注册回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6847098/