2015-01-11 134 views
0

我正在處理一個通用的矩陣類。 我重載+功能,這樣,當是做:模板函數重載C++

  1. 矩陣=標量*矩陣
  2. 矩陣=矩陣*標量
  3. 矩陣=矩陣*矩陣

試圖做它就像那樣(函數重載): 這是一個正確的方法嗎?

template<class T> 
class Matrix 
{ 
    std::vector< std::vector<T> > mat; 
    size_t rows , cols; 

public: 
    Matrix(){} 
    Matrix(const std::string){ } 
    Matrix(const size_t r, const size_t c, const std::vector<T> v){ } 
    Matrix(const Matrix& other); 

    Matrix<T> operator=(const Matrix<T> &other) { } 

    Matrix<T> operator+(const Matrix<T> &other) const{} 

    friend Matrix<T> operator*(const T &mat, const Matrix<T> &scalar) { } 

    friend Matrix<T> operator*(const Matrix<T> &mat, const T &scalar) { } 

    friend Matrix<T> operator*(const Matrix<T> &mat, const Matrix<T> &other) { } 

此外,我會很高興知道,如果我的聲明有一些問題。 感謝您的幫助。

+0

提醒:您需要在頭文件中執行執行和聲明 – Gabriel

+1

這將是很好的顯示您的問題,而不是請求代碼審查。 – Emadpres

+2

我懷疑你的賦值操作符應該返回'Matrix&'。另外,不知道爲什麼'std :: string'在那個alternate-ctor中是'const';嘗試一個const引用。 – WhozCraig

回答

0

如果你想重載operator*允許

  1. 矩陣=標*矩陣
  2. 矩陣=矩陣*標
  3. 矩陣=矩陣*矩陣

您需要定義這些三個操作符重載作爲矩陣類周圍命名空間中的函數:

class Matrix { ... }; 
Matrix operator*(Scalar const& s, Matrix const& m) { ... } 
Matrix operator*(Matrix const& m, Scalar const& s) { ... } 
Matrix operator*(Matrix const& m1, Matrix const& m2) { ... } 

在你的情況,你聲明的運算作爲類,它不一樣的,因爲它實際上宣告自由功能使他們friendsfriend功能。這取決於實施是否friend實際上是必要的。如果不是的話,我會在課堂以外的地方將它們移到清晰的位置,但請記住,您需要使用template<typename T>。關於其他代碼,沒有任何明顯的破壞,但它只是真實代碼的摘錄。

+0

我試過了,但是我怎麼會知道前兩個狀態。 1.模板 矩陣矩陣 ::運算符*(常量矩陣&標量) 2.模板 矩陣矩陣 ::運算符*(常量T&標量) 這樣? –

+0

我不知道你到底嘗試了什麼,但似乎在自由函數和成員函數之間存在一些混淆。我會盡力澄清我寫的內容。 –

+0

通過說「朋友實際上是必要的」你怎麼樣?什麼時候有必要? –

-2

看着這個問題,有一個替代的想法。

matrix = scalar * matrix 
matrix = matrix * scalar 
matrix = matrix * matrix 

另一種方法是使用函數對象並將其傳遞給矩陣類,使函數對象能夠處理算法的細節......這允許您如果需要添加更多的後來。

運算符鏈在上面的代碼中也很方便,因此,通過引用返回重載的運算符。

+0

在二進制操作中引用是指什麼? – juanchopanza

+0

如果你打算做到這一點,我的意思是結果矩陣對象。 – basav