c++ - operator = overload in template class -


im working on matrix template class, , should write "=" operator overload. im trying delete matrix appears in left side of '=', , return new 1 equals matrix appears in right side of '='.

because can't delete "this" distructor, delete "manually" in function. should make new matrix, therefor make new 1 ("temp") , return it. prblem "temp" return, doesn't set in matrix appears in left side of '='.

the code:

matrix<int> m (3, 4);     matrix<int> m2(2, 5);     m2 = m; 

this main part.

the function:

template<class t> matrix<t> & matrix<t>::operator=(matrix<t>& mat) {     if (this==&mat)     {         return *this;     }      (int = 0; < this->rows; i++)     {         delete[] this->mat[i];     }      delete[] this->mat;      matrix<t> * temp = new matrix<t>(mat.rows, mat.cols);      (int = 0; < temp->rows; i++)         (int j = 0; j < temp->cols; j++)         {             temp->mat[i][j] = mat.mat[i][j];         }      return *temp; }   template<class t> matrix<t>::matrix(int row, int col) {     rows = row;     cols = col;     mat = new t*[rows];     (int = 0; < rows; i++)     {         mat[i] = new t[cols];     }     rester(*this); } 

thx!!

use std::vector storage (instead of manal new , delete), , accept copy assignment operator generated compiler. it's easy.


if absolutely want implement copy assignment yourself, learning, express copy assignment in terms of copy construction.

to that, first define noexcept swap operation:

// in class definition: friend void swap( matrix& a, matrix& b )     noexcept {     using std::swap;     // swap data members here } 

then copy assignment operator can expressed simply

// in class definition auto operator=( matrix other )     -> matrix& {     swap( *this, other );     return *this; } 

it's popular, idiom, because it's simple yet exception safe.


instead of returning reference, adds verbosity , possible marginal inefficiency no gain, might want use void return type. however, historical reasons, containers in standard library require copy assignment operator return reference self.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -