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

后端 未结 3 1472
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 17:53

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

Object* objects[] =
{
    new Object(/*constructor parameters         


        
相关标签:
3条回答
  • 2020-12-30 18:28

    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.

    0 讨论(0)
  • 2020-12-30 18:51
    Object* objects[20];
    
    for(int i=0; i<20; /*number of objects*/ i++)
    {
        objects[i] = new Object(/*constructor parameters*/);
    }
    
    0 讨论(0)
  • 2020-12-30 18:52

    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.

    0 讨论(0)
提交回复
热议问题