简体   繁体   English

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

[英]How to delete this 2D Array in C++

I've absolutely no idea why my delete codes inside the destructor won't be able to functionally well. 我完全不知道为什么析构函数中的删除代码无法正常运行。 I hope u guys can help me for this. 我希望你们能为此提供帮助。

Thank you so much! 非常感谢!

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;
}

You are not initializing anything in your default constructor. 您没有在默认构造函数中初始化任何东西。 That means that the destructor will go mad on a default constructed object. 这意味着析构函数将对默认的构造对象发狂。 You are also not disabling the copy constructor, which is not functioning with your class, because if you have copied an object, it will try to delete the same table twice. 您也不会禁用不能与您的类一起使用的复制构造函数,因为如果您复制了一个对象,它将尝试两次删除同一张表。 Change it as follows, for example 例如,如下更改

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;
          }

}

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

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