简体   繁体   English

使用for循环C ++声明对象数组

[英]Declare an array of objects using a for loop c++

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? 无论如何,有没有使用某种循环(最好是for循环)来声明这些? Something like: 就像是:

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

But with proper syntax? 但是使用正确的语法?

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. 这提供了异常安全性,并减轻了堆的压力。

Object* objects[20];

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

Points in C++ can be used as arrays. C ++中的点可以用作数组。 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. 丹尼斯·M。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM