重载*=矩阵c++的运算符

overload *= operator for matrices c++

本文关键字:运算符 c++ 矩阵 重载      更新时间:2023-10-16

我试图重载矩阵的*=运算符这是我为2个矩阵的*运算符所做的函数

    template <class T>
    Matrix<T> Matrix<T>::operator*(const Matrix& other) const
    {
        assert(cols == other.rows) ;
        Matrix<T> temp(rows, other.cols) ;
        for(unsigned i = 0 ; i < rows ; i++)
        {
            for(unsigned j = 0 ; j < other.cols ; j++)
            {
                temp.matrix[i][j] = 0 ;
                for(unsigned k= 0 ; k < other.rows ; k++)
                {
                    temp.matrix[i][j] = temp.matrix[i][j] + (matrix[i][k]*other.matrix[k][j]) ;
                }
            }
        }
        return temp ;
    }

这是我的*=操作员实现

template <class T>
Matrix<T> Matrix<T>::operator*=(const Matrix& other) const 
{
    assert(cols == other.rows) ;

    for(unsigned i = 0 ; i < rows ; i++)
    {
        for(unsigned j = 0 ; j < other.cols ; j++)
        {
            matrix[i][j] = 0 ;
            for(unsigned k= 0 ; k < other.rows ; k++)
            {
                matrix[i][j] = matrix[i][j] + (matrix[i][k]*other.matrix[k][j]) ;
            }
        }
    }
    return *this ;
}

我不知道我的*=实现中的语义错误在哪里,因为它编译并运行,但输出远高于预期的

问题是,在对其中一个项求值时,不能将乘积的结果分配给它,因为这会破坏您仍然需要计算其他元素的原始值。

由于您有一个可工作的二进制*,实现*=的简单方法是将其作为*this = *this * other

可以有捷径,但需要矩阵具有特定的结构(对角线、三角形等)。在一般情况下,这是更简单、更安全的方法。

当然,我认为你们的矩阵至少是可复制和可赋值的。如果你也可以移动,你也可以获得性能。

您正在覆盖运算符的LHS,同时仍在尝试计算乘积。

以矩阵为例:

1  0
0  1

2 0 
0 2

对于i = 0j = 0,结束制作第一个矩阵;

0  0
0  1

在你开始乘法之前。你知道在那之后你不会得到正确的答案。

我不知道是否有一种技术可以用来将两个矩阵相乘,并将结果保存在LHS(或RHS)中。