You never update mat.size
in your operator>>
overload, so although you read 4 values in, the matrix thinks it is empty and prints nothing out.
Also, very importantly, if the matrix passed to the operator>>
overload already has data then you will leak memory, because you do not free that data and you assign a new pointer to mat.mdata
You could do something like this instead:
istream & operator >> (istream &is, matrix &mat) {
int rows, columns;
is >> rows >> columns;
if (!is)
return is; // couldn't read rows and cols
matrix tmp(rows, columns);
if(tmp.size>0) {
cout << "Enter " << tmp.size << " values (top row, second row... last row - left to right)" << endl;
N.B. do not allocate a new array here, that was done in the constructor above.
// Copy values into new array
for(int i=0;i<tmp.size;i++) {
is >> tmp.mdata[i];
}
}
if (is) // read all values successfully
mat = tmp;
This requires that your assignment operator works correctly, so it's a good time to ensure that! Another option would be to swap:
mat.swap(tmp);
This requires a correct matrix::swap(matrix&)
member function, which is a useful thing to have for many reasons.
return is;
}
Notice I put in error-checking to ensure you actually read the expected data from the stream.
The bug in your assignment operator is here:
int size=0;
// Now copy size and declare new array
size=m.getcols()*m.getrows();
You declare a new local variable called size
, and update that variable. That means this->size
never gets updated. You do not want to declare a new size
, you just want to update the member variable, so change the above to:
// Now copy size and declare new array
size=m.getcols()*m.getrows();