C++创建对象数组(来自不同类)
我需要创建一个包含多个类的对象的数组。
示例
class baseClass
{
//
};
class first : baseClass
{
//
};
class second : baseClass
{
//
};
如何创建可以在其中保存 first
和/或 second
对象的数组?
这对我来说有点像是家庭任务,所以我被迫使用数组,我已经搜索过并知道它是通过 boost 库等完成的,但我在这里别无选择......
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最佳实践是创建指向基类的智能指针数组(最好是 Boost 或 C++11 版本之一)。使其成为指针数组可以消除访问对象时“切片”对象的风险。使用智能指针可以降低内存泄漏的风险。使其成为基类指针意味着任一派生类都可以安全地存储在那里。
The best practice for that would be to create an array of smart pointers - preferably either one of the Boost or C++11 versions - to the base class. Making it a pointer array eliminates the risk of "slicing" your objects when you access them. Using smart pointers reduces the risk of memory leaks. Making it a base class pointer means that either derived class can be stored there safely.
这是最简单也是最危险的方法。您必须小心对象的生命周期,以避免泄漏或双重释放。您还必须小心数组的分配和释放,特别是当您必须在运行时更改大小时。
这改进了前面的示例,因为向量为您处理数组的内存,但您仍然必须小心使用基类指针。
这是另一项改进,消除了为对象手动分配或释放内存的需要,并且在第一或第二次访问对象方面是类型安全的。你不能将一种物体误认为是另一种物体。
使用此选项,您仍然可以混淆不同类型的对象,但它仅使用标准库,并且您仍然不必管理分配的对象的生命周期。但它确实使用了 C++11。
另外,如果您不需要动态数组,可以使用
std::array<...,size>
std::array,10> array3;
与baseClass *array[10];
相比,运行时的空间或时间开销绝对为零,而且更安全。 (零开销,假设实现得当)This is the simplest and most dangerous way. You have to be careful about the lifetime of the objects in order to avoid leaking or double freeing. You also have to be careful with the array's allocation and deallocation, especially if you have to change the size at runtime.
This improves the previous example because the vector handles the memory of the array for you, but you still have to be careful with the baseClass pointers.
This is another improvement that eliminates the need to manually allocate or deallocate memory for the objects, and it's type safe in terms of accessing the objects as firsts or seconds. You can't mistake one kind of object for another.
With this option you can still confuse objects of different types for each other, but it uses only the standard library and you still don't have to manage the lifetime of the objects you allocate. It does use C++11 though.
Also, if you don't need a dynamic array you can use
std::array<...,size>
std::array<std::unique_ptr<baseClass>,10> array3;
has absolutely zero space or time overhead at runtime overbaseClass *array[10];
, and is much safer. (zero overhead, assuming a decent implementation)如果您无法使用库,则需要一个指针数组,例如:
并且不会发生切片。 (不要忘记
删除
所有内容)If you can't use libraries you need an array of pointers like:
and no slicing will occur. (don't forget to
delete
everything)