0
使用「this」關鍵字的我已經定義了一個模板類,和重載運營商,以這樣的方式在模板類
template<class T = bool>
class SparseMatrix
{
public:
SparseMatrix(int msize);
//Multiplication by vectors or matrices
SparseMatrix<double> operator *(SparseMatrix<T> &s);
//Matrix exponentiation
SparseMatrix<double> pow(int n);
};
運營商的具體形式並不重要,我想。隨着運營商超載,現在我可以做這樣的事情:
int main(void)
{
int i;
SparseMatrix<bool> s = SparseMatrix<bool>(4);
SparseMatrix<bool> t = SparseMatrix<bool>(4);
//Here goes some code to fill the matrices...
SparseMatrix<double> u = t*s; //And then use the operator
return 0;
}
這工作得很好。沒有錯誤,它返回正確的結果,等等。但是現在,我要填充類的pow
方法,用這種方法:
template<class T>
SparseMatrix<double> SparseMatrix<T>::pow(int n)
{
if (n == 2)
{
return (this * this); //ERROR
}
else
{
int i=0;
SparseMatrix<double> s = this * this;
while (i < n-2)
{
s = s * this;
i++;
}
return s;
}
}
然而,當我去main
和喜歡寫東西SparseMatrix<double> u = t.pow(2);
我得到說錯誤invalid operands of types 'SparseMatrix<bool>*' and 'SparseMatrix<bool>*' to binary 'operator*'
。正如我之前所說的,乘法是爲bool
矩陣定義明確的,所以,編譯器爲什麼抱怨?我是否在使用this
?我該如何解決這個錯誤?
謝謝你的幫助。
你似乎忘記了'this'是對象的*指針*。如果你真的閱讀錯誤信息(提到'SparseMatrix *'的類型),應該非常明顯。 –
順便說一句,所有'const'都不見了。 – Jarod42
如果你實現'operator * =()'和'operator *()',你會發現它更容易和更高效。 –