Declare an array of objects using a for loop c++

强颜欢笑 提交于 2019-12-20 15:33:11

问题


Okay. So I have declared an array of objects, and I have manually defined them using this code:

Object* objects[] =
{
    new Object(/*constructor parameters*/),
    new Object(/*constructor parameters*/)
}; 

Is there anyway to use some kind of a loop (preferably a for loop) to declare these? Something like:

Object* objects[] =
{
    for(int i=0; i<20; /*number of objects*/ i++)
    {
        new Object(/*constructor parameters*/);
    }
}; 

But with proper syntax?


回答1:


I strongly suggest using a standard library container instead of arrays and pointers:

#include <vector>

std::vector<Object> objects;

// ...

void inside_some_function()
{
    objects.reserve(20);
    for (int i = 0; i < 20; ++i)
    {
        objects.push_back(Object( /* constructor parameters */ ));
    }
}

This provides exception-safety and less stress on the heap.




回答2:


Object* objects[20];

for(int i=0; i<20; /*number of objects*/ i++)
{
    objects[i] = new Object(/*constructor parameters*/);
}



回答3:


Points in C++ can be used as arrays. Try something like this:

// Example
#include <iostream>

using namespace std;

class Object
{
public:
    Object(){}
    Object(int t) : w00t(t){}
    void print(){ cout<< w00t << endl; }
private:
    int w00t;
};

int main()
{
    Object * objects = new Object[20];
    for(int i=0;i<20;++i)
        objects[i] = Object(i);

    objects[5].print();
    objects[7].print();

    delete [] objects;
    return 0;
}

Regards,
Dennis M.



来源:https://stackoverflow.com/questions/5226352/declare-an-array-of-objects-using-a-for-loop-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!