I am writing a class matrix for practice but a situation have come to make me a problem, see.
I want to do is
cout << (mymatrix + 5.0);
but my related overloaded operators are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
ostream & operator <<(ostream & os, matrix & m){ //overloaded << to enable console output of matrix object
m.console(os); //use already class defined method to output matrix on console
return os; //<< must return ostream object to enable casecading
}//----------------operator <<
matrix matrix::operator +(double scalar) const{ //overloaded + to enable addition of a matrix with a scalar
matrix temp(totalrows, totalcols);
for(int rows = 0; rows < totalrows; rows++){ //nested loop to process element by element keep adding scalar element by
//element to values obtained from current matrix and keep storing results in temporary matrix
for(int cols = 0; cols < totalcols; cols++){
temp.thematrix[rows][cols] = (this->thematrix[rows][cols] + scalar);
}//----------------for
}//--------------for
return temp;
}//-------------operator + (double)
works fine too (I've overloaded = operator (with self-assignment test) too)
but cout << (mymatrix + 5.0); does not work and I know because I need to return reference according to my overloaded << operator but if I do that in overloaded + operator then I just can't do because I can't return a local variable by reference from within + overloaded operator
I can do one more thing overload << operator to take object matrix instead of taking a reference to matrix but then I get some kind of linker error
Please tell me what is the original solution to this problem?
also what if I didn't declare my matrix as constant like
matrix m;
const matrix m2;
now if function receives type "const matrix &" then it can't receive "m" and if it receives "matrix &" then it can't receive "m2"
and in most of my program I'm using matrix objects which are not constant
A reference to a const can refer to non-const objects just fine. The opposite is not true.
The reason you need it to be const is because when you do (mymatrix + 5.0) this will return a temporary object. A temporary object will not bind to a reference that refers to a non-const object.