如何在C ++中删除这个2D数组

时间:2010-02-07 12:54:53

标签: c++

我完全不知道为什么析构函数中的删除代码无法正常运行。我希望你们可以帮助我。

非常感谢你!

class Array2D
{
      public: 
      Array2D();
      Array2D(int,  int);
      ~Array2D();

      private:
      int row;
      int col;
      int **p;
};

Array2D::Array2D()
{
      // Default Constructor
}


Array2D::Array2D(int rows, int cols)
{
     this -> row = rows;
     this -> col = cols;

     p = new int* [row]; 
     for(int i=0; i< row; i++)
          p[i] = new int[col];

     // Fill the 2D array
     for (int i = 0; i < row; i++)
          for (int j = 0; j < col; j++)
          {
               p[i][j] = rand () % 100;
          }
}    


Array2D::~Array2D()
{
     // I'm using this way to delete my 2D array.
     // however, it won't work!

     for (int i = 0; i < row; i++)
     {
          delete[]p[i];
     }
     delete[]p;
}

1 个答案:

答案 0 :(得分:3)

您没有在默认构造函数中初始化任何内容。这意味着析构函数会对默认的构造对象发疯。您也没有禁用复制构造函数,因为如果您复制了一个对象,它将尝试删除同一个表两次。更改如下,例如

class Array2D
{
      public: 
      Array2D();
      Array2D(int,  int);
      ~Array2D();

      private:
      int row;
      int col;
      int **p;

      void initialize(int rows, int cols);

      // disable copy functions (make private so they cannot 
      // be used from outside).
      Array2D(Array2D const&);
      Array2D &operator=(Array2D const&);
};

Array2D::Array2D()
{
     initialize(0, 0);
}


Array2D::Array2D(int rows, int cols)
{
     initialize(rows, cols);
}    

void Array2D::initialize(int rows, int cols) {
     this -> row = rows;
     this -> col = cols;

     p = new int* [row]; 
     for(int i=0; i< row; i++)
          p[i] = new int[col];

     // Fill the 2D array
     for (int i = 0; i < row; i++)
          for (int j = 0; j < col; j++)
          {
               p[i][j] = rand () % 100;
          }

}