【问题标题】:C++ queue to store multiple type objectsC++队列存储多种类型对象
【发布时间】:2016-03-23 04:10:14
【问题描述】:

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

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

如何将两个不同的类存储在一个数据结构中,并在检索它们时访问它们的原始方法?

或者有其他选择吗

【问题讨论】:

    标签: c++ oop generics inheritance queue


    【解决方案1】:

    对象切片会在这里发生。您的 child 类对象将被切片为 base 类类型,因为您在调用 push_back 时是按值传递的。您需要使用基类的指针或智能指针的queue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 2017-11-13
      相关资源
      最近更新 更多