[英]overload *= operator for matrices c++
我正在嘗試重載矩陣的* =運算符這是我的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 = 0
和j = 0
,您將結束制作第一個矩陣;
0 0
0 1
在開始乘法之前。 您知道那之后您將無法獲得正確的答案。
我不知道是否有一種技術可用於將兩個矩陣相乘並將結果保留在LHS(或RHS)中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.