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

时间:2013-06-03 09:48:27

标签: c++ polymorphism

我正在为不同类型的协议消息编写接口类。我不能重写基本协议代码,以便为每个协议提供一个通用接口我正在创建一个基类,它具有一个通用接口,每个特定协议都有包装类。

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

message* msg = new protocol_a_msg(a_msg);

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

但是,最终我需要获取底层协议消息。所以我想编写一个获取底层消息的虚函数。即在基本消息类中:

<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;
}

1 个答案:

答案 0 :(得分: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();
};
相关问题