所以我试图删除析构函数中的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;
}
谢谢!
答案 0 :(得分:1)
因为所有的矩阵运算符都是“按值”获取参数,而你没有“复制构造函数”。
导致破坏问题的那个是作为参数传递的那个(假设是副本)。
您如何在(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);