c++ - 如何在c ++中使用构造函数动态声明对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8462895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to dynamically declare an array of objects with a constructor in c++
提问by user972276
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!
我会使用向量等,但我的老师告诉我们尽可能使用基本数组。上面的解决方案实际上是从我老师写的一些代码中得到的。谢谢大家的帮助!
采纳答案by Nawaz
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. Neither manual allocation, nor manual deallocation. Plus, you can know the number of elements by calling arr.size()
anytime. You always know how many elements the vector contains. You can also add elements anytime, just by calling .push_back()
member function as:
vector 也很好,因为现在您不需要自己管理内存。既不是手动分配,也不是手动释放。另外,您可以通过arr.size()
随时调用来了解元素的数量。您总是知道向量包含多少个元素。您还可以随时添加元素,只需调用.push_back()
成员函数:
arr.push_back(MyClass(20,30));
And now you can access elements, just like you access array, i.e 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
});
回答by fefe
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 的回答所示。
回答by Connor Farrell
One way I've done this in the past is using a double pointer.
我过去这样做的一种方法是使用双指针。
MyClass ** myvar;
myvar = new Myclass*[num]
for(int i = 0; i < 4; i++){
*(myvar+i) = new Myclass(i);}
Works with pretty much any control structure you can imagine, the only setback is that the objects aren't necessarily going to be consecutive on the heap.
适用于您可以想象的几乎任何控制结构,唯一的挫折是对象不一定在堆上是连续的。
回答by Akib Imtiaz
You can do something like this too:
你也可以做这样的事情:
MyClass *myVar[num];
for(int i = 0; i < num; i += 1)
{
myVar[i] = new MyClass(0, 0);
}
回答by amiralwaled
@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);
}
回答by Marc De Scheemaecker
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);
}