c++ - 如何使用 typedef 函数指针注册回调

标签 c++ compiler-errors function-pointers observer-pattern

我正在尝试使用 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/

相关文章:

c# - 从 C# 调用 Cygwin 的 Seg 错误

c++ - 使用括号会在声明新节点时出错

c - 如何声明受限函数指针参数

c++ - 复杂的 C 声明

c++ - 使用 OpenCV 的 C++ 图像的 SNR

c++ - 部分模板特化的下标运算符重载

c++ - 将 3d 对象排列成圆形

android - Xamarin 函数错误

c++ - 类中没有声明成员函数 - 基本编译错误

更改返回的可变参数函数指针