【问题标题】:How to correctly return result of matrixes multiplication如何正确返回矩阵乘法的结果
【发布时间】:2015-03-04 13:36:15
【问题描述】:

我有一个布尔矩阵类。 在析构函数中释放内存无法正常工作,它会尝试删除无效指针 - 正如我注意到的那样,当我尝试乘法时会发生这种情况。

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

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

谢谢

【问题讨论】:

  • 为什么不使用向量?

标签: c++ pointers operator-overloading


【解决方案1】:

我认为您正在尝试删除堆栈上的 [] 内存。

而不是

Matrix res(rows, that.cols);

试试

Matrix res=new Matrix(rows, that.cols);

【讨论】:

    【解决方案2】:

    重载复制构造函数来复制整个数组,所以当函数删除它的类的本地实例时,它会删除它自己的矩阵,而main中的函数将拥有它的矩阵副本(注意,如果你这样离开它,什么你从main中得到函数和变量的结果,你在main中等于函数的结果,指向完全相同的内存,这就是你需要复制构造函数的原因)

    【讨论】:

    • 是的,我忘记了我使用指针,所以它们将被共享,我认为使用 bool 向量作为堆栈也是另一种解决方案。谢谢
    • 是的,我只是在堆栈上使用了布尔向量,而不是在堆中
    • 试图编写复制构造函数,但想不出任何正确的复制构造函数来解决无效指针问题
    • BoolMatrix::BoolMatrix(other &amp;t) { rows = t.rows; cols = t.cols items = new bool*[rows]; for (size_t i = 0; i &lt; rows; i++) { items[i] = new bool[cols]; for (size_t j = 0; j &lt; cols; j++) items[i][j] = t[i][j]; } } 这是正确的方式
    【解决方案3】:

    重载 '=' 运算符并像 a=a*a 一样使用它;析构函数必须是

    BoolMatrix::~BoolMatrix()
    {
    
            for (size_t i = 0; i < rows; i++)
            {       
    
                delete [] items[i];
            }   
    
            delete[] items;
    
        }
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      相关资源
      最近更新 更多