如何正确返回矩阵乘法运算的结果

How to correctly return result of matrixes multiplication

本文关键字:运算 结果 何正确 返回      更新时间:2023-10-16

我得到了一个布尔矩阵的类。析构函数中的内存分配不正确,它试图删除无效指针——正如我所注意到的,当我尝试相乘时会发生这种情况。

在运算符*中,我返回本地对象作为结果,而该部分会导致无效指针——所以程序在析构函数中删除时崩溃——问题是为什么会在这段代码中发生这种情况?以及如何正确返回结果?这是代码:

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