Following is code for adding two matrix.For a 2 by 2 matrix it is giving first two value as garbage value and next two as same.
The problem is with overloaded+operator function(shaded ).Before returning if I cout the added matrix it prints fine but after returning it is not printing correctly.Even it is not returning *this correctly.
Code:#include<iostream.h> #include<conio.h> class matrix { private: int *ptr,n; public: matrix(int num):n(num) { //constructor ptr=new int[n*n]; } void getmatrix(); void putmatrix(); matrix operator+(matrix &); ~matrix() { //destructor delete[]ptr; } }; void matrix:: getmatrix() { cout<<"Enter the matrix"; for(int i=0;i<=n-1;i++) { for(int j=0;j<=n-1;j++) cin>>ptr[i*n+j]; } } void matrix::putmatrix() { for(int i=0;i<=n-1;i++) { for(int j=0;j<=n-1;j++) cout<<ptr[i*n+j]<<"\t"; cout<<endl; } } matrix matrix::operator+(matrix &second) { matrix temp(n); for(int i=0;i<=n-1;i++) { for(int j=0;j<=n-1;j++) temp.ptr[i*n+j]=ptr[i*n+j]+second.ptr[i*n+j]; } //couting temp here works fine return(temp);//Even it does not return(*this) correctly } int main() { int m,n; cout<<"Enter no of rows and columns"; cin>>m>>n; if(m!=n) cout<<"Addition not possible"; else { matrix m1(n),m2(n),m3(n); m1.getmatrix(); m1.putmatrix(); m2.getmatrix(); m2.putmatrix(); m3=m1+m2; m3.putmatrix(); } getch(); return(0); }



LinkBack URL
About LinkBacks


