我如何在.h文件中销毁这个2D数组
How do I destruct this 2D array in the .h file?
所以我试图删除析构函数中的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);
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 使用指针算法修改函数中的 2D 数组
- 在C++中初始化和打印 2D 数组
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- C++ 2D 数组写入多个位置
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 如何从initializer_list初始化 2D 数组
- 交换函数不是在 C++ 中交换 2D 数组的元素