How to add two matrices in c++ -


i write class , have problem adding matrices. know have overload operator +, don't know how exactly. ideas ?

 class cmatrix   {     private:             int rows;             int columns;             float* pdata;      public:             cmatrix(void);             cmatrix(int rows, int columns);                             void setelement(int row, int column, float element);             float getelement(int row, int column);    ...};     istream& operator>>(istream& in, cmatrix& matrix)      { in >> matrix.rows; in >> matrix.columns;  for(int = 0; < matrix.rows; i++)     for(int j = 0; j < matrix.columns; j++)         in >> *(matrix.pdata + * matrix.columns + j);  return in;     }         cmatrix::cmatrix(int rows, int columns)     {     rows = rows;     columns = columns;     pdata = new float[rows * columns];      float* pend = &pdata[rows * columns];      for(float* p = pdata; p < pend; p++)             *p = 0.0;       }       void cmatrix::setelement(int row, int column, float element)     {       *(pdata+  row * columns + column) = element;       }      float cmatrix::getelement(int row, int column)      {        return *(pdata + row * columns + column);       } 

overloaded operators '<<' ,'>>' , have problem operator +.

unfortunatelly have less 10 reputation...so if write:

 cmatrix operator+(const cmatrix &lhs, const cmatrix &rhs)     {  cmatrix result (rows,columns); for(int i=0; <rows ; i++) for( int j=0; j<columns; j++)  result.setelement(i,j)  = lhs.getelement(i,j) + rhs.getelement(i,j);    return result;        }    int main()    { const int n = 10, m = 5;  cmatrix m1(n, m);      cmatrix m2(n, m);  for(int = 0; < n; i++)     for(int j = 0; j < m; j++)         m1.setelement(i, j, (float)(i * m + j));      for(int = 0; < n; i++)         for(int j = 0; j < m; j++)         m2.setelement(i, j, (float)(i * m + j));     cout<<m1+m2;  // doesn't work    help, did @ last... 

unless need access private members of cmatrix perform computation, recommend create non-member function following prototype:

cmatrix operator+(const cmatrix &lhs, const cmatrix &rhs) {   // work    // may need throw exceptions based on incompatibilities between   // matrix configurations (i.e., dimensions) } 

you should add copy constructor, destructor, , assignment operators (maybe move constructor , move assignment well) or consider disabling these operations. if not, run serious issues compiler supplied defaults if code employs them.

you need add destructor, because leak memory if not.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -