C++队列来存储多个类型的对象

C++ queue to store multiple type objects

本文关键字:类型 对象 队列 存储 C++      更新时间:2023-10-16

到目前为止,我的最佳想法是使用基类并用不同类型的对象对其进行子类化。在这种情况下,有两个子类具有相似的方法,因此这似乎是合乎逻辑的。我通过向上转换到基类来存储对象,但在使用其子类方法访问对象时遇到了问题。这是我的头文件和主要方法:

#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