[英]how to dynamically declare an array of objects with a constructor in c++
I was wondering if it was possible to create an array of objects when the object needs things passed into it for the constructor.我想知道当对象需要为构造函数传递给它的东西时,是否可以创建一个对象数组。 I want something like this:
我想要这样的东西:
MyClass *myVar;
myVar = new MyClass[num]; // I would like to specify the array size after declaration
int i = 0;
for(i = 0;i < num;i++)
myVar[i] = new MyClass(0,0); // I would also like to populate the array with new objects
I know that this works:我知道这有效:
MyClass *myVar;
myVar = new MyClass[num];
but this only works when the constructor has nothing passed into it.但这仅在构造函数未传入任何内容时才有效。 Is what I am trying to do possible?
我正在尝试做的可能吗? If so, how do I do it?
如果是这样,我该怎么做?
EDIT: I found out how to do it with using arrays.编辑:我发现了如何使用数组来做到这一点。 Here is how I did it:
这是我如何做到的:
MyClass **myVar;
myVar = new MyClass *[num];
for(i = 0;i < num;i++)
myVar[0] = new MyClass(0,0);
I would use vectors and such but my teacher has told us to use basic arrays whenever possible.我会使用向量等,但我的老师告诉我们尽可能使用基本数组。 The above solution I actually got from some code my teacher wrote.
上面的解决方案实际上是从我老师写的一些代码中得到的。 Thank you all for your help!
谢谢大家的帮助!
MyClass *myVar;
myVar = new MyClass[num];
Actually in this form you cannot invoke constructor which takes parameter(s).实际上,在这种形式中,您不能调用带有参数的构造函数。 It is not allowed by the language specification.
语言规范不允许这样做。
However, if you use std::vector
, which I recommend you to use, then you can create a vector calling non-default constructor as:但是,如果您使用
std::vector
,我建议您使用它,那么您可以创建一个调用非默认构造函数的向量:
#include <vector> //header file where std::vector is defined
std::vector<MyClass> arr(num, MyClass(10,20));
It creates a vector of num
elements, each element is created by calling copy-constructor of the class, passing MyClass(10,20)
as argument to it.它创建一个由
num
元素组成的向量,每个元素都是通过调用类的复制构造函数创建的,并将MyClass(10,20)
作为参数传递给它。
The vector is also good because now you dont need to manage memory yourself. vector 也很好,因为现在您不需要自己管理内存。 Neither manual allocation, nor manual deallocation.
既不手动分配,也不手动解除分配。 Plus, you can know the number of elements by calling
arr.size()
anytime.另外,您可以随时调用
arr.size()
来知道元素的数量。 You always know how many elements the vector contains.您总是知道向量包含多少个元素。 You can also add elements anytime, just by calling
.push_back()
member function as:你也可以随时添加元素,只需调用
.push_back()
成员函数:
arr.push_back(MyClass(20,30));
And now you can access elements, just like you access array, ie by using index:现在您可以访问元素,就像访问数组一样,即通过使用索引:
f(arr[i]); // 0 <= i < arr.size();
Additionally, you can use iterators which facilitate idiomatic programming, enabling you to use various algorithmic functions from <algorithm>
header as:此外,您可以使用迭代器来促进惯用编程,使您能够使用来自
<algorithm>
标头的各种算法函数:
#include <algorithm> //header file where std::for_each is defined
std::for_each(arr.begin(), arr.end(), f);
where f
is function which takes one argument of type MyClass&
(or MyClass const &
) depending on what you want to do in f
.其中
f
是一个函数,它接受一个MyClass&
(或MyClass const &
)类型的参数,具体取决于您想在f
做什么。
In C++11, you can use lambda as:在 C++11 中,您可以将 lambda 用作:
std::for_each(arr.begin(), arr.end(), [](const MyClass & m)
{
//working with m
});
In C++0x, this grammar works, which can call the non-default constructor in new expression:在 C++0x 中,这种语法有效,它可以在 new 表达式中调用非默认构造函数:
MyClass *myVar;
myVar = new MyClass[2]{{10, 20},{20, 30}};
But I doubt if it works when the number of elements in available only at run time.但我怀疑它是否适用于仅在运行时可用的元素数量。
The vector approach would be better, as shown in Nawaz's answer.矢量方法会更好,如 Nawaz 的回答所示。
Pointer to pointer is equivalent to 1. array of pointers, and 2. vector<T*> vector of pointers.指向指针的指针等效于 1. 指针数组和 2. vector<T*> 指针向量。 One way I've done this in the past is using a double pointer.
我过去这样做的一种方法是使用双指针。 This approach eliminates the overhead of vector data structure and preferred memory efficient is needed.
这种方法消除了向量数据结构的开销,并且需要优先的内存效率。
MyClass ** myvar;
myvar = new Myclass*[num]
for(int i = 0; i < num; i++){
*(myvar+i) = new Myclass(i);}
Works with pretty much any control structure you can imagine.几乎适用于您可以想象的任何控制结构。 The drawback is that the allocation of memory is not contiguous and my affect speed for large number of num.
缺点是内存分配不连续,大量num影响速度。
You can do something like this too:你也可以做这样的事情:
MyClass *myVar[num];
for(int i = 0; i < num; i += 1)
{
myVar[i] = new MyClass(0, 0);
}
Actually, you can use a placement new to handle this:实际上,您可以使用新的展示位置来处理此问题:
MyClass * myVar;
myVar = reinterpret_cast<MyClass *>(new char[num * sizeof(MyClass)]);
int i = 0;
for (i = 0; i < num; i++) {
new(&myVar[i]) MyClass(0,0);
}
@Nawaz answer is really good about using vectors, but didn't work for me because it create vector of the same objects (all of them reference to the same object) @Nawaz 的答案非常适合使用向量,但对我不起作用,因为它创建了相同对象的向量(所有这些都引用了同一个对象)
class Graph
{
public:
Graph(long V); // none default Constructor
}
std::vector<Graph> myGraph;
for (int i = 0; i < T; i++) // read all graphs
{
Graph newGraph(N);
myGraph.push_back(newGraph);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.