Objects of different classes in a single vector?(单个向量中不同类别的对象?)
问题描述
在我的代码中,我有一组对象:
class Sphere { ...类平面{ ......
而且我需要在 vector
中使用它们的集合(它们都有不同的类型).我如何将不同类的对象添加到 vector
?
Sphere 和 Plane 需要一个通用的基类型,或者你的向量需要由 void*
组成.>
常见的基本类型(更好):
class Shape { ... };类球体:公共形状{ ... };类平面:公共形状{ ... };std::vector<形状*>形状;
或 void*
(不太好):
std::vector形状;
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 different types) in a vector
. How would I add objects of different classes to a vector
?
Sphere and Plane would need a common base type, or your vector would need to be composed of void*
's.
Common base type (better):
class Shape { ... };
class Sphere : public Shape { ... };
class Plane : public Shape { ... };
std::vector<Shape*> shapes;
or void*
's (not great):
std::vector<void*> shapes;
这篇关于单个向量中不同类别的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:单个向量中不同类别的对象?


- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01