Making a vector of instances of different subclasses

前端 未结 4 918
猫巷女王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:24

    You cannot literally create a vector of objects of an abstract class, because the vector template needs to be able to tell the compiler, at compile time, the size of its element. However, you can get what you want by keeping a vector of pointers to objects rather than a vector of objects as such.

    Update: Abstract classes as such have known size. It is actually instances of their most derived types whose sizes are unknown at compile time. (Thanks @LuchianGrigore and @MooingDuck for pointing this out.)

提交回复
热议问题