Objects of different classes in a single vector?

前端 未结 7 2286
情书的邮戳
情书的邮戳 2020-12-09 22:58

In my code, I have a set of objects:

class Sphere { ...
class Plane { ...
...

And I need to use a collection of them (they will all have di

7条回答
  •  旧时难觅i
    2020-12-09 23:42

    The classes would need to have a common base class, e.g.:

    class MyBase { };
    class Sphere : public MyBase { };
    class Plane : public MyBase { };
    

    Then in order to store polymorphic objects in a vector, you must store a pointer to them (because they can be different sizes from the base class). I recommend using a std::shared_ptr or std::unique_ptr (or use Boost if C++0x isn't available).

    std::vector > v;
    v.push_back(new Sphere());
    v.push_back(new Plane());
    

    If there is no common base, you'd have to use void*, or find a different way to do this.

提交回复
热议问题