C++,没有<vector>的对象数组 [英] C++, array of objects without <vector>
本文介绍了C++,没有<vector>的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 C++ 中创建一个不使用 STL 的对象数组.
I want to create in C++ an array of Objects without using STL.
我该怎么做?
如何创建没有无参数构造函数(默认构造函数)的 Object2 数组?
How could I create array of Object2, which has no argumentless constructor (default constructor)?
推荐答案
如果有问题的类型具有无参数构造函数,请使用 new[]
:
If the type in question has an no arguments constructor, use new[]
:
Object2* newArray = new Object2[numberOfObjects];
不要忘记在不再需要数组时调用 delete[]
:
don't forget to call delete[]
when you no longer need the array:
delete[] newArray;
如果没有这样的构造函数,使用operator new
来分配内存,然后就地调用构造函数:
If it doesn't have such a constructor use operator new
to allocate memory, then call constructors in-place:
//do for each object
::new( addressOfObject ) Object2( parameters );
同样,不要忘记在不再需要数组时释放它.
Again, don't forget to deallocate the array when you no longer need it.
这篇关于C++,没有<vector>的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文