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;
}
你能告訴我什麼,我需要改變或修復嗎?
但是,你有什麼問題? – paweln66
閱讀http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom然後從頭開始。 –
和/或用'std :: vector'實現你的矩陣,讓它自動處理。 –