It was too literally painful reading through the unformatted, unindented code (yes, literally, I now have a headache and eye strain). So I gave up half way through, nor is there any guarantee I've read things properly, so...
in the overloaded operators you are returning a reference to a temporary, so if this worked for you, you were (un)lucky. Since your operators are member variables, making them const is pointless, this means your use of temp is also unnecessary. The purpose of an operator is to operate. If you don't want it to change the object use a global operator that accepts const references instead. Also, you can't synthesize operator+= or -=, if + and - are const. If you insist on doing it this way, you'll need to return an object.
...
matrix& operator+(const matrix&);// Overload +
...
//EDIT: since I moaned about indentation as well...
//Overload +
matrix& matrix::operator+(const matrix& m)
{
if ((rows==m.get_rows()) && (columns==m.get_columns()))
{
constint Size=m.get_rows()*m.get_columns();
for (int i=0; i<Size; i++)
{
mdata[i]+=m.mdata[i];
}
return *this;
}
else
{
cout<<"Error: Matrices must have the same dimensions."<<endl;
}
}
Sorry - I didn't know how to paste in my formatted/indented code. I will learn how to next time I ask a question here.
Thanks so much for your help, that's worked!
I'm not sure I understand your explanation about not needing const before the function definition (forgive my naivety!). Could you explain it again please?
operator* should not affect this - that is, it should be suffixed with const. What you have written is better suited as an implementation of operator*=. operator* on the other hand, returns a third matrix without modifying either of the inputs.
Right, i see. But I thought for the * overloading I'd defined a temporary matric to store the multiplication and then returned it. Why doesn't that work?
Because operator functions are just like any other function. When you write a + b, it is the same as a.operator+(b) - in fact the latter is actually valid syntax.
If you want to avoid confusion, overload operators as non-member functions (that is, don't define them inside the class):