我正在尝试为矩阵重载 *= 运算符这是我为 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/