具有不同返回类型的虚函数
virtual function with varying return types
我正在为不同类型的协议消息编写接口类。我不能重写基本协议代码,所以为了给每个协议一个公共接口,我正在为每个特定协议创建一个带有包装类的公共接口的基类。
所以每个包装器类将有一个公共接口,然后在我的代码中处理协议消息,我可以使用多态性,即
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();
};
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 在 c++ 中将函数返回类型指定为模板参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何避免模板函数返回类型重复?
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在某些情况下从函数返回类型中删除 cv 限定符?
- 模板类内模板类的函数返回类型
- 为什么函数返回类型中不允许参数推导?
- 函数返回类型之前的"define"
- C++推断要隐式调用的模板函数返回类型
- 具有不同模板参数的函数返回类型
- 当函数返回类型为父类时,如何返回子类的对象?
- C++:在原型中声明"auto"函数返回类型仍然会导致在扣除错误之前使用"auto&quo
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 函数返回类型中的模板类型推断
- 嵌套模板类返回类型在 C++ 中的头文件中函数返回类型的语法
- C++重写 void 函数返回类型会导致生成失败
- 从函数内部推断函数返回类型
- C++嵌套类函数返回类型和命名空间