从基类更改为派生类的最佳方法

Best way to change from base class to derived class

本文关键字:最佳 方法 派生 基类      更新时间:2023-10-16

我知道这个论坛上有各种各样的问题,但我仍然不能完全弄清楚我需要做什么(在阅读了各种其他帖子之后)。所以我决定寻求进一步的建议!

我有一个消息类层次结构,类似于(省略大部分细节):

class MsgBase
{
    public:
        uint8_t getMsgType(void);
    protected: // So that derived classes can access the member
        char _theMsgData[100];
}
class MsgType1 : public MsgBase
{
}
class MsgType2 : public MsgBase
{
}

所以发生的是我收到了一个消息数据块,我用它来创建我的消息。但是,在读出消息类型之前,我不知道要创建哪个消息。所以最后是:

MsgBase rxMsg(rxData);
if (rxMsg.getMsgType() == 1)
{
    // Then make it a MsgType1 type message
}
else if (rxMsg.getMsgType() == 2)
{
    // Then make it a MsgType2 type message
}

这是我卡住的地方。从我所读到的,我不能动态地从基到派生。因此,我当前的选择是实例化一个全新的派生类型(这似乎效率低下),即:

if (rxMsg.getMsgType() == 1)
{
    // Now use the same data to make a MsgType1 message.
    MsgType1 rxMsg(rxData);
}

是否有一种方法可以将数据视为基类,以便确定其类型,然后将其"molymorph"转换为所需的派生类型?

谢谢,饲料

什么是rxData ?我假设它只是一个数据团,在创建任何消息对象之前,您应该解析它以确定消息类型。根据消息数据是否始终具有相同的长度,您应该考虑使用std::arraystd::vector来传递数据blob。

typedef std::vector<char> MsgDataBlob;
class MsgBase
{
    public:
        uint8_t getMsgType();
        MsgBase(MsgDataBlob blob) : _theMsgData(std::move(blob)) {}
    protected: // So that derived classes can access the member
        MsgDataBlob _theMsgData;
};
//derived classes here...
//this could be either a free function or a static member function of MsgBase:
uint8_t getMessageType(MsgDataBlob const& blob) { 
  // read out the type from blob
}
std::unique_ptr<MsgBase> createMessage(MsgDataBlob blob) {
  uint8_t msgType = getMessageType(blob);
  switch(msgType) {
    case 1: return make_unique<MsgDerived1>(std::move(blob));
    case 2: return make_unique<MsgDerived2>(std::move(blob));
    //etc.
  }
}

如果您希望消息返回数据,但例如MsgType1应该使其全部小写,而msgtype2应该全部大写,您可以在MsgBase中创建一个虚拟函数,例如,

virtual char *getData();

和此函数应该在子类中重新实现,以便它对数据执行您希望它执行的操作。这样,当你在基类指针上调用这个函数时,你将获得重新实现的功能,这取决于调用时实际指针的类型。