c++ - 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
方法,甚至C++
是C++11 standard
. FromC++11 standard
最好使用标准库提供的std::function,这也可以分配一个 lambda 函数。
推荐阅读
- csv - 如何使用 symfony 4 下载 csv 文件?
- serialization - Json.NET:序列化图表系列只返回“类型名称”
- java - 在 JFrame 中居中 JButton - Java
- javascript - 如果在 javascript 中总是相同的结果
- javascript - window.location.href 不重定向
- java - 显示来自 4 个具有不同 ID 的源的表面视图的 4 个相机预览,并从每个源捕获图像
- ios - 如何访问变量以观察 SwiftUI UI 测试的变化?
- php - 如何将特定类别的产品页面重定向到 Woocommerce 中的购物车页面
- java - 在两个属性上比较两个 POJO 类
- sql - 函数参数,Postgres