我正在尝试重载矩阵的* =运算符这是我的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
。
可以有快捷方式,但是需要矩阵具有特定的结构(对角,三角形等)。在一般情况下,这是更简单,更安全的方法。
当然,我假设您的矩阵至少是可复制和可分配的。而且即使它也可以移动,您也可以获得性能。
关于c++ - 重载* =矩阵C++的运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25898434/