首页 > 解决方案 > C ++如何存储函数指针?

问题描述

这是我的代码:

class Opcodes {
public:
    Opcodes() = default;
    virtual ~Opcodes() = default;
    virtual void Initialize() = 0;
    virtual void ValidateAndSetServerOpcode(ServerOpcode serverOpcode, void(WorldSession::*HandlerFunction)(std::vector<std::byte>& data)) = 0;
    class PacketHandler{
    public:
        PacketHandler() = default;
        ServerOpcode serverOpcode;
        std::vector<std::byte> data;
        void(WorldSession::*HandlerFunction)(std::vector<std::byte>& data);
        void Run();
    private:
        WorldSession* _session;
    };

protected:
    PacketHandler* opcodeHandler[NUM_MSG_TYPES];
};

让我们专注于这个功能:

void ValidateAndSetServerOpcode(ServerOpcode serverOpcode, void(WorldSession::*HandlerFunction)(std::vector<std::byte>& data))

如何void(WorldSession::*HandlerFunction)(std::vector<std::byte>& data)将第二个参数存储ValidateAndSetServerOpcode在指针成员中PacketHandler

我试过void(WorldSession::*HandlerFunction)(std::vector<std::byte>& data);了,但这不是正确的方法。

这是我尝试在内部分配它的方法ValidateAndSetServerOpcode

opcodeHandler[serverOpcode]->HandlerFunction = HandlerFunction;

但是它不起作用。当我尝试这样分配时,我会崩溃。

甚至有可能吗?如果可以,怎么办?

标签: c++function-pointersmember-function-pointers

解决方案


函数指针的定义是正确的,但也许你没有初始化你使用的指针

无论如何,您的方法是一个C方法,甚至C++C++11 standard. FromC++11 standard最好使用标准库提供的std::function,这也可以分配一个 lambda 函数。


推荐阅读