我已经使用OMNeT ++的消息定义工具创建了消息类型WowMessage。假设类Server的重写的handleMessage函数始终收到WowMessage消息,该消息最初被作为cMessage处理。我该如何从cMessageWowMessage进行类型转换,以便可以使用已定义的成员字段和WowMessage类型的函数?

void Server::handleMessage(cMessage *msg)
{
    // Receives WowMessage which is subclassed from cMessage...
    // TODO: typecast from cMessage to WowMessage
    forwardMessage(msg);
}

void Server::forwardMessage(WowMessage *msg)
{
    send(msg, "port$o", msg->getDestAddress() - 1);
}

最佳答案

例如,使用dynamic_cast

WowMessage * wowMsg = dynamic_cast<WowMessage *>(msg);
if (wowMsg) {
   // msg is an instance of WowMessage
} else {
   // another message
}

08-15 21:57