具有不同返回类型的虚函数

virtual function with varying return types

本文关键字:函数 返回类型      更新时间:2023-10-16

我正在为不同类型的协议消息编写接口类。我不能重写基本协议代码,所以为了给每个协议一个公共接口,我正在为每个特定协议创建一个带有包装类的公共接口的基类。

所以每个包装器类将有一个公共接口,然后在我的代码中处理协议消息,我可以使用多态性,即

message* msg = new protocol_a_msg(a_msg);

然后我可以使用带有消息*参数的函数来处理等等,这很好。

然而,最终我需要获得底层协议消息。所以我想写一个虚函数来获取底层的信息。在基本消息类中:

<type> get_msg() = 0;

但是问题是各不相同的。这是否意味着我不能有虚函数,因为返回类型不同?

如果我不能这样做,我将需要转换为特定的协议包装器类型并使用特定的函数。这是可行的,但我想知道什么是最好的方法。

下面是我的代码:
#include <iostream>
class message {
public:
   enum msg_type { PROTOCOLTYPE, BINARYTYPE, UNKNOWNTYPE };
   message(msg_type type = PROTOCOLTYPE) : type_(type) {}
   void set_type(msg_type type) { type_ = type; }
   msg_type get_type() const { return type_; }
   msg_type type_;
   virtual ~message() {}
// Can I make this a generic get underlying data virtual function?
 //  virtual underlying_msg get_msg() const { return <underlying_msg>; }
   //may also need a set_msg(msg) - or can initialise protocol msg in ctor
};

//this is existing protocol code which I cannot change
class protocol_a {
public:
   enum a_type { SMALL, MEDIUM, LARGE };
   protocol_a(a_type a) : atype_(a) { }
   const char* get_data() { 
      static const char* const names[] = { "SMALL", "MEDIUM", "LARGE" };
      return names[atype_];
   }
protected:
   a_type atype_;
};
class protocol_a_msg : public message {
public:
   protocol_a_msg(protocol_a * a) : proto_(a) {}
   protocol_a* get_msg() const { return proto_; }
   protocol_a* proto_;
};

int main() {
    protocol_a a_msg(protocol_a::SMALL);
    protocol_a_msg* pa_msg = new protocol_a_msg(&a_msg);
    //retrieve underlying protocol_a msg
    protocol_a* a = pa_msg->get_msg();
    const char* s = a->get_data();
    std::cout << "protocol_a data=" << s << std::endl;
    delete [] pa_msg;
    return 0;
}

你可以这样做:

class A {};
class B : A {};
class C : A {};
class IFoo
{
public:
    virtual A * func() = 0;
};
class BFoo
{
public:
    virtual B * func();
};
class CFoo
{
public:
    virtual C * func();
};