value of b1 changes after the + operation. Tried to prevent that , but no luck.
Code:#include <iostream> #include <algorithm> using namespace std; template <class T> class Array2D { T* data; int w, h; public: Array2D(int X, int Y) : w(X), h(Y) { data = new T[w*h]; } ~Array2D() { if (data != NULL) { delete [] data; data = NULL; } } T& operator ()(int Col, int Row) { return data[Row*w+Col]; } Array2D<T>& operator+( Array2D<T>& m) { //Array2D<int> c(w,h); //Array2D<int>& result = c; Array2D& result = m; for (int r=0;r<h;r++) { for (int c=0;c<w;c++) { result(c,r) = (*this)(c,r)+m(c,r); } } return result; } int width() {return w;} int height() {return h;} }; int main( ) { int c = 5; int r = 6; Array2D<int> b(c,r); Array2D<int> b1(c,r); for(int j=0; j<r; j++) { for(int i=0; i<c; i++) { b(i,j) = 2; b1(i,j) = 1; } } //value of b1 changes after this line. Tried to prevent that , but no luck. Array2D<int>& a1 = b + b1; for(int j=0; j<r; j++) { for(int i=0; i<c; i++) { std::cout << a1(i,j) << "\t"; } std::cout << "\n"; } return 0; }




Reply With Quote