簡體   English   中英

類實例在右側的運算符重載

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM