Dynamically allocating an array of objects

前端 未结 7 1689
挽巷
挽巷 2020-11-22 13:05

I have a class that contains a dynamically allocated array, say

class A
{
    int* myArray;
    A()
    {
        myArray = 0;
    }
    A(int size)
    {
           


        
7条回答
  •  迷失自我
    2020-11-22 13:33

    Why not have a setSize method.

    A* arrayOfAs = new A[5];
    for (int i = 0; i < 5; ++i)
    {
        arrayOfAs[i].SetSize(3);
    }
    

    I like the "copy" but in this case the default constructor isn't really doing anything. The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that.
    OR
    The SetSize could delete the original m_array.

    void SetSize(unsigned int p_newSize)
    {
        //I don't care if it's null because delete is smart enough to deal with that.
        delete myArray;
        myArray = new int[p_newSize];
        ASSERT(myArray);
    }
    

提交回复
热议问题