![](/img/trans.png)
[英]Overloading assignment operator when the object is on the right-hand side of the assignment
[英]Overloading of operators with class instance as right-hand side
我正在嘗試對Matrix類中的*運算符進行重載。
如果是Matrix * something,我有一個可以做到((int,double ...)
我正在尋找使它成為另一面的東西,即*矩陣
這就是我嘗試過的
template<class T>
bool operator*(Matrix<T>& other ){
Matrix<T> mat(other.rows,other.columns);
for(int i=0;i<other.rows;i++){
for(int j=0;j<other.columns;j++){
T temp=other.get(i,j);
temp=temp*(this);
mat.set(i,j,temp);
}
}
return mat;
}
這就是適用於Matrix * something的東西
Matrix<T>& operator*(const T & num){
Matrix<T> mat(rows,columns);
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
T temp=(matrix[i][j]);
temp=temp*num;
mat.set(i,j,temp);
}
}
return mat;
}
您應該將其設為非成員,即您是在Matrix
類之外編寫的:
template<class T>
Matrix<T> operator*(const T& num, const Matrix<T>& mat) {
return mat * num; // invoke existing implementation of Matrix * something
}
請注意, operator*
應按值返回結果。 您的實現中存在一個錯誤,您將懸空引用返回到局部變量mat
。
請注意,此表格要求num
的類型為T
因此,例如在您的示例中
Matrix<Rational> mat;
mat = 3 * mat;
它不會編譯,因為3
不是Rational
。
您可以做的是使用身份技巧將num
參數放在非推導上下文中,以便將其從int
轉換為Rational
:
template<class T>
Matrix<T> operator*(typename boost::mpl::identity<T>::type const& num, const Matrix<T>& mat) {
return mat * num; // invoke existing implementation of Matrix * something
}
identity
在哪里
template<typename T>
struct identity { typedef T type; };
或者你可以做
template<class T, class U>
Matrix<T> operator*(const U& num, const Matrix<T>& mat) {
return mat * num; // invoke existing implementation of Matrix * something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.