如何正确返回矩阵乘法运算的结果
How to correctly return result of matrixes multiplication
我得到了一个布尔矩阵的类。析构函数中的内存分配不正确,它试图删除无效指针——正如我所注意到的,当我尝试相乘时会发生这种情况。
在运算符*中,我返回本地对象作为结果,而该部分会导致无效指针——所以程序在析构函数中删除时崩溃——问题是为什么会在这段代码中发生这种情况?以及如何正确返回结果?这是代码:
#include <iostream>
using namespace std;
class BoolMatrix
{
private:
bool ** items;
public:
size_t rows, cols;
BoolMatrix(size_t = 0, size_t = 0);
~BoolMatrix();
BoolMatrix operator * (const BoolMatrix &) const;
//some other members
};
BoolMatrix::BoolMatrix(size_t r, size_t c) : rows(r), cols(c)
{
items = new bool*[r];
for (size_t i = 0; i < r; i++)
{
items[i] = new bool[c];
for (size_t j = 0; j < c; j++)
items[i][j] = 0;
}
}
BoolMatrix::~BoolMatrix()
{
if (items)
{
for (size_t i = 0; i < rows; i++)
{
if (items[i])
delete[] items[i];
items[i] = NULL;
}
delete[] items;
items = NULL;
}
}
BoolMatrix BoolMatrix::operator * (const BoolMatrix& that) const
{
//NxM * MxK = NxK
if (cols != that.rows)
return NULL;
Matrix res(rows, that.cols);
for (size_t i = 0; i < rows; i++)
{
for (size_t j = 0; j < that.cols; j++)
for (size_t l = 0; l < that.rows; l++)
res.items[i][j] = (res.items[i][j] + items[i][l]*that.items[l][j]) != 0;
}
return res;
}
int main(int argc, char *argv[])
{
size_t n;
cin >> n;
BoolMatrix a(n, n);
//matrix reading code
a*a;
return 0;
}
感谢
我认为发生的情况是您试图删除堆栈上的[]内存。
代替
Matrix res(rows, that.cols);
尝试
Matrix res=new Matrix(rows, that.cols);
重载复制构造函数来复制整个数组,所以当函数删除它的类的本地实例时,它将删除它自己的矩阵,而main中的函数将有它的矩阵副本(注意,如果你这样留下它,你从main中得到的函数和变量的结果,你在main中等于函数的结果,指向完全相同的内存,这就是为什么你需要复制构造函数)
重载'='运算符,并像使用a=a*a一样使用它;并且析构函数必须是
BoolMatrix::~BoolMatrix()
{
for (size_t i = 0; i < rows; i++)
{
delete [] items[i];
}
delete[] items;
}
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 使用C++中的模板和运算符重载执行矩阵运算
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- GCC本机矩阵运算库
- 算术运算的结果类似于:C浮点变量中的1/3
- 相同的算术运算在 C++ 和 Python 中给出不同的结果
- C++随机数的逻辑运算结果
- 浮点运算结果的重现性
- 如何正确返回矩阵乘法运算的结果
- 确定两个矢量类型或一个矢量类型与标量类型之间的二进制运算结果的正确大小类型
- 使用浮点值和铸造的算术运算的错误结果 - 差异很大,我想这不是准确值的情况(429497)?
- 为什么 bool 显示正确的位顺序,而直接输出移位运算结果却不显示?
- 按位运算结果和布尔值
- 为什么C++和Java中的这种浮点运算会产生不同的结果
- 算术运算打印错误的结果
- 在Java中,按位运算的结果是否取决于endianes?用C或C++怎么办
- 如果算术运算的结果未存储在内存中会发生什么情况
- 按位运算的意外结果 为什么 (1 | 1 & 2) 给出 1 而不是 2?