2016-01-09 36 views
1

我想寫一個operator =模板對象的重載, 我正在創建一個模板矩陣。我需要,如果我會做這樣的事情:m[i][j] = m2[i][j];它應該與任何類型的參數和對象。重載operator =在C++模板(對象)

這是我的代碼:

拷貝構造函數:

template<class T> 
inline Matrix<T>::Matrix(const Matrix& other) 
{ 
    this->_rows = other._rows; 
    this->_cols = other._cols; 

    this->_array = new T*[rows]; 

    for (int i = 0; i < rows; i++) 
     this->_array[i] = new T[cols]; 

    // Copy 'temp' to 'this' 
    for (int i = 0; i < this->_rows; i++) 
     for (int j = 0; j < this->_cols; j++) 
      this->_array[i][j] = other._array[i][j]; 

} 

operator=超載:

template<class T> 
inline T& Matrix<T>::operator=(const T &obj) 
{ 
    // Is the same 
    if (this == &obj) 
    { 
     return *this; 
    } 
    // Go to copy constructor of 'T' 
    T* temp = new T(obj); 
    return temp; 
} 

你能告訴我什麼,我需要改變或修復嗎?

+2

但是,你有什麼問題? – paweln66

+0

閱讀http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom然後從頭開始。 –

+0

和/或用'std :: vector '實現你的矩陣,讓它自動處理。 –

回答

0

你的代碼的問題在於你試圖通過引用T來指定Matrix<T>,所以Matrix<T>對象不會受到賦值的影響。

在設計中,您必須始終從您的賦值運算符中返回Matrix<T>&。所以代碼看起來像這樣。

template<class T> 
inline Matrix<T>& Matrix<T>::operator=(const T &obj) 
{ 
    // Some object member assignment 
    m_SomeMember = obj; 

    return *this; 
} 

你在這種情況下,不能檢查對象爲dublicates因爲TMatrix<T>,它只是重新分配對象,具有不同類型的成員。

如果您仍然想要將另一個Matrix<T>對象分配給Matrix<T>。您的代碼必須如下所示:

template<class T> 
inline Matrix<T>& Matrix<T>::operator=(const Matrix<T>& obj) 
{ 
    if (this == &obj) 
    { 
     return *this; 
    } 
    // Performing deep copying 
    m_SomeMember = obj.m_SomeMember; 
    return *this; 
} 

我也檢測到您的複製構造函數存在問題。您必須使用:的

template<class T> 
inline Matrix<T>::Matrix(const Matrix<T>& other) 
{ 
    /* Copy constructors body */ 
} 

代替

template<class T> 
inline Matrix<T>::Matrix(const Matrix& other) 
{ 
    /* Copy constructors body */ 
}