Making a vector of instances of different subclasses

前端 未结 4 914
猫巷女王i
猫巷女王i 2020-12-06 14:17

Tried searching, nothing returns( i ithink).

Is it possible to make a vector of an abstract class?

For example, I have the super class Unit.

And I Ha

4条回答
  •  情歌与酒
    2020-12-06 14:40

    Since each of those objects is different sizes, the proper way to do this is a container containing pointers to the base class Unit, (and be sure it has a virtual destructor.

    Option 1: boost::ptr_vector (requires boost libraries, which you should have anyway)

    ptr_vector units;
    units.push_back(new Soldier());
    

    Option 2: std::vector> (requires C++11 compiler)

    std::vector> units;
    units.emplace_back(std::unique_ptr(new Soldier()));
    

提交回复
热议问题