2012-11-22 45 views
0

我有一個矩陣類。我超載乘法運算符,但它的工作只有當我打電話矩陣標量;不適用於標量矩陣。我怎樣才能解決這個問題?如何重載乘法運算符?

#include <iostream> 
#include <stdint.h> 

template<class T> 
class Matrix { 
public: 
    Matrix(unsigned rows, unsigned cols); 
    Matrix(const Matrix<T>& m); 
    Matrix(); 
    ~Matrix(); // Destructor 

Matrix<T> operator *(T k) const; 

    unsigned rows, cols; 
private: 
    int index; 
    T* data_; 
}; 

template<class T> 
Matrix<T> Matrix<T>::operator *(T k) const { 
    Matrix<double> tmp(rows, cols); 
    for (unsigned i = 0; i < rows * cols; i++) 
     tmp.data_[i] = data_[i] * k; 

    return tmp; 
} 

template<class T> 
Matrix<T> operator *(T k, const Matrix<T>& B) { 
    return B * k; 
} 

編輯


我實現什麼chillsuggested,但我發現了以下錯誤:

main.cpp: In function ‘int main(int, char**)’: 
main.cpp:44:19: error: no match for ‘operator*’ in ‘12 * u2’ 
main.cpp:44:19: note: candidate is: 
lcomatrix/lcomatrix.hpp:149:11: note: template<class T> Matrix<T> operator*(T, const Matrix<T>&) 
make: *** [main.o] Error 1 
+0

我認爲你需要做的另一重載:檢查這http://stackoverflow.com/questions/10354886/simple-c-how-to-overload-the-multiplication-operator-so-that-floatmyclass -an – Pavenhimself

+1

順便說一下,這個'Matrix tmp(rows,cols);'應該是這個'Matrix tmp(rows,cols);'。 – chill

回答

2

定義的類,它只是反轉的參數之外的operator*。並宣佈其他operator*const

template<typename T> Matrix<T> operator* (T k, const Matrix<T> &m) { return m * k; } 
+0

我試過了你的選擇,但是我得到他下面的錯誤: main.cpp:44:19:錯誤:'12 * u2''operator *'不匹配main.cpp :44:19:note:candidate: lcomatrix/lcomatrix.hpp:149:11:note:template Matrix operator *(T,const Matrix &) –

+0

很可能您的矩陣沒有使用int實例化,類型。 – chill

+0

這是問題,謝謝 –

3

不要讓運營商成員。定義一個operator*=作爲Matrix的成員,然後在其實現中使用*=定義兩個免費的operator*

0

類成員operator *運行在它的相應的對象(左側),調用M * scalar相當於A.operator*(scalar) - 這顯然如果切換順序,因爲你沒有操作*爲標定義也並不適用。您可以創建一個全局的operator *實現,它接受標量作爲第一個(左)操作數和矩陣。在執行內部切換命令並調用您的inclass類operator *。例如: -

template <class T> 
Matrix<T> operator *(T scalar, const Matrix<T> &M) 
{ 
    return M * scalar; 
} 
+2

這是一場災難的祕訣 - 你會返回一個對象的引用,這個對象很快就會消失。 – chill

+0

@chill我編輯了 – SomeWittyUsername