【问题标题】:Cannot declare field 'pair' to be of abstract type 'System'无法将字段“对”声明为抽象类型“系统”
【发布时间】:2014-10-04 17:10:35
【问题描述】:

我的SystemManager 有一个System 类的映射,其中每个系统都映射到systype 类型

typedef string systype;

在头文件中,声明了这个map

class SystemManager
{
    public:
        SystemManager();
        ~SystemManager();

        map<systype, System> systems;

        System* getSystemPointer(systype);
};

我尝试在构造函数中将DrawSystem(派生自System 的类)添加到我的“系统映射”中:

SystemManager::SystemManager()
{
    systems["Draw"] = DrawSystem();
}

这给了我错误:

不能将归档的“pair&lt;systype, System&gt;::second”声明为抽象类型系统

我不知道是什么原因造成的。

这是我的SystemDrawSystem 课程,以防万一:

class System
{
    public:
        System();

        systype type;
        vector<cptype> args;
        virtual void update(vector<Cp*>) = 0; //= 0 is for pure virtual function
};

class DrawSystem : public System
{
    friend class Game; //allows to draw on render window
    public:
        DrawSystem();

        void update(vector<Cp*>);
};

【问题讨论】:

    标签: c++ abstract-class virtual abstract pure-virtual


    【解决方案1】:

    当您在以下行中按值 (map&lt;systype, System&gt; systems;) 存储 Systems 时:

    systems["Draw"] = DrawSystem();
    

    slicing 发生,而您实际上是在尝试创建一个抽象的 System 实例。

    这里最简单的解决方法是改用指针:

    map<systype, System*> systems;
    

    但也可以考虑使用 std::unique_ptr 之类的东西,以避免手动内存管理。例如:

    map<systype, unique_ptr<System>> systems; //pre C++11: put an extra space between >>
    

    和:

    systems["Draw"] = unique_ptr<DrawSystem>(new DrawSystem());
    

    甚至更好 - 不使用 new(正如 sjdowling 在 cmets 中所建议的那样):

    systems["Draw"] = std::make_unique<DrawSystem>();
    

    【讨论】:

      【解决方案2】:

      System是抽象类,因为他有纯虚函数。您不能创建 System. 尝试执行以下操作

      map<systype, System*> systems;
      ...
      systems["Draw"] = new DrawSystem();
      ...
      ~SystemManager()
      {
          // call delete for each item in systems
      }
      

      【讨论】:

        猜你喜欢
        • 2013-11-15
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 2012-07-23
        • 1970-01-01
        • 2016-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多