0

基本上我想创建一个对象数组,其大小从一个类传递到另一个类,即

Object * ArrayOfObjects = new Object[Size];

虽然成功创建了一个数组,但它不允许我使用构造函数。

如何创建我的对象数组,然后定义数组中的每个对象?

4

3 回答 3

3

Once you allocate memory for the array you can then assign to it by looping:

for (int i = 0; i < Size; ++i)
{
    ArrayOfObjects[i] = Object( /* call the constructor */ );
}

Or you can use a vector to do the same but with more ease of use:

std::vector<Object> ArrayOfObjects = { Object(...), Object(...) };
于 2013-06-02T02:49:12.983 回答
1

你所问的实际上可能不是最好的事情——那就是使用 std::vector 之类的东西,但在幕后他们要做的就是你的问题。

然后您可以分配或放置新的每个条目:

for (size_t i = 0; i < Size; ++i)
{
     // Option 1: create a temporary Object and copy it.
     ArrayOfObjects[i] = Object(arg1, arg2, arg3);
     // Option 2: use "placement new" to call the instructor on the memory.
     new (ArrayOfObjects[i]) Object(arg1, arg2, arg3);
}
于 2013-06-02T06:10:07.870 回答
0

Once you allot memory, as you did. You initialize each object by traversing the array of objects and call its constructor.

#include<iostream>
using namespace std;
class Obj
{
    public:
    Obj(){}
    Obj(int i) : val(i)
    {
        cout<<"Initialized"<<endl;
    }
    int val;
};
int allot(int size)
{

    Obj *x= new Obj[size];
    for(int i=0;i<10;i++)
        x[i]=Obj(i);

     //process as you need
     ...
}
于 2013-06-02T02:50:06.680 回答