C++队列来存储多个类型的对象
C++ queue to store multiple type objects
到目前为止,我的最佳想法是使用基类并用不同类型的对象对其进行子类化。在这种情况下,有两个子类具有相似的方法,因此这似乎是合乎逻辑的。我通过向上转换到基类来存储对象,但在使用其子类方法访问对象时遇到了问题。这是我的头文件和主要方法:
#include <iostream>
#include <queue>
#include <stdlib.h>
#include <string>
#include <sstream>
#define STATIC 0
#define DYNAMIC 1
// Base class Msg
class Msg {
public:
void set_type(int);
int get_type();
virtual std::string repr();
virtual int* get_data();
protected:
int type;
};
// Derived class StaticMsg
class StaticMsg: public Msg {
public:
void set_data();
std::string repr() override;
int* get_data() override;
protected:
int data[10];
};
class DynamicMsg: public Msg {
public:
DynamicMsg();
void set_data(int sz);
std::string repr() override;
int* get_data() override;
protected:
int len, *data;
};
int main(void) {
StaticMsg smsg,new_smsg;
DynamicMsg dmsg,new_dmsg;
smsg.set_type(STATIC);
smsg.set_data();
dmsg.set_type(DYNAMIC);
dmsg.set_data(21);
queue <Msg> q;
q.push(smsg);
q.push(dmsg);
cout <<q.front().get_type() << endl;
// FIXME call to repr() is causing segmentation fault
cout <<q.front().repr()<<endl;
cout << "here!"<<endl;
}
如何将两个不同的类存储在一个数据结构中,并在检索它们时访问它们的原始方法?
或者是否有其他选择
对象切片将在此处进行。您的child
类对象将被切片为base
类类型,因为您在调用push_back时传递值。您需要使用基类的指针或智能指针的queue
。
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象
- 接受泛型列表类型对象的参数
- C++-将模板类型对象强制转换为特定的数据类型
- 试图在C++中打印存储在类型对象数组中的信息