返回指向不带 typedef 的内联函数的指针

returning pointer to a function inline without typedef

我 运行 遇到 C++ 语法错误,我必须 return 一个指向内联函数的指针。

struct Note{}

Observer.hpp

class Observer {
    protected:
        void (*notify)(Note *note); // should this be *(*notify...)?
    public:
        void (*(*getNoteMethod)())(Note *note);
};

Observer.cpp

void (*Observer::getNoteMethod())(Note*) { //error: non-static data member defined out-of-line
    return this->notify;
}

我收到此错误,错误:非静态数据成员定义超出范围

我是 C++ 新手,正在尝试正确定义 return 函数签名。

问题出在成员函数(returns 函数指针)的声明语法上。声明为:

class Observer {
    protected:
        void (*notify)(Note *note);
    public:
        void (*getNoteMethod())(Note *note);
};

最好通过usingtypedef提前声明函数指针类型,看起来更清晰。例如

class Observer {
    using function_pointer_type = void(*)(Note*); // the function pointer type
    protected:
        function_pointer_type notify;             // the data member with function pointer type
    public:
        function_pointer_type getNoteMethod();    // the member function returns function pointer
};

// Out-of-class member function definition
Observer::function_pointer_type Observer::getNoteMethod() {
    return this->notify;
}