我如何在.h文件中销毁这个2D数组

How do I destruct this 2D array in the .h file?

本文关键字:2D 数组 文件      更新时间:2023-10-16

所以我试图删除析构函数中的2D sq_matrix。然而,它给了我一个内存错误:

    *** glibc detected *** ./hw1.out: free(): invalid pointer: 0x0000000000d6ccb0 ***
    ======= Backtrace: =========
    /lib64/libc.so.6[0x31dd675f3e]
    /lib64/libc.so.6[0x31dd678d8d]
    ./hw1.out[0x4011af]
    ./hw1.out[0x400f54]
    /lib64/libc.so.6(__libc_start_main+0xfd)[0x31dd61ed1d]
    ./hw1.out[0x400a69]
    ======= Memory map: ========
    00400000-00402000 r-xp 00000000 fd:02 99359246    
/*                        some memory map here  */
    Aborted (core dumped)

这是我把代码放入的。h文件:

#ifndef SQUAREMATRIX_H
#define SQUAREMATRIX_H
#include <iostream>
using namespace std;
template<class T>
    class SquareMatrix{
     public:
      int size;
      T** sq_matrix;
      SquareMatrix(int s){
          size = s;
          sq_matrix = new T*[size];
          for(int h = 0; h < size; h++){
            sq_matrix[h] = new T[size];
          }
      }
      ~SquareMatrix(){
        for(int h = 0; h < size; h++){
            delete[] sq_matrix[h];
        }
         delete[] sq_matrix; 
      } 
      void MakeEmpty(){
         //PRE: n < width of sq matrix
         //POST: first n columns and rows of sq_matrix is zero
      }
      void StoreValue(int i, int j, double val){
          //PRE: i < width; j < height
          //POST: sq_matrix[i][j] has a non-null value
      }
      void Add(SquareMatrix s){
         //PRE: this.SquareMatrix and s are of the same width and height
         //POST: this.SquareMatrix + s
      }
      void Subtract(SquareMatrix s){
         //PRE: this.SquareMatrix and s are of the same width and height
         //POST: this.SquareMatrix - s
      }
      void Copy(SquareMatrix s){
         //PRE: s is an empty matrix
         //POST: s is a ixi matrix identical to this.SquareMatrix
      }
    };

我所做的就是在构造函数外创建一个2d数组并在构造函数内分配内存。然后,我尝试删除析构函数中的指针,但它仍然给我一个错误。下面是我的主要方法:

#include <iostream>
#include "SquareMatrix.h"
using namespace std;
int main(){
  int size;
  int val;
  cout << "Enter the width and height of the square matrix: ";
  cin >> size;
  SquareMatrix<int> sq1(size);
  SquareMatrix<int> sq2(size);
  return 0;
}

谢谢!

因为你所有的矩阵运算符的参数都是"按值",而你没有一个"复制构造函数"

在销毁时引起问题的是作为参数传递的那个(假定是复制)。

如何用(const SquareMatrix& rhs)来声明你的操作?像

  void Add(const SquareMatrix& s){
     //PRE: this.SquareMatrix and s are of the same width and height
     //POST: this.SquareMatrix + s
    if(s.size==this->size) {
      for(int i=0; i<this->size; i++) {
        for(int j=0; j<this->size; j++) {
          this->sq_matrix[i][j]+=s.sq_matrix[i][j];
        }
      }
    }
  }

被称为

SquareMatrix<int> m1(3), m2(3);
m1.Add(m2);