Reputation: 23
I am receiving the following error:error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Matrix')
And the related code is like:
Matrix Matrix::operator+(const Matrix &b){
Matrix C(r,c);
int i,j;
if(b.r!=r||b.c!=c)
printf("invalid operation!");
else {for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
C.data[i][j]=data[i][j]+b.data[i][j];
}
cout<<endl;
}
}
return C;
}
ostream & operator<<(ostream &out, Matrix &A){
int i,j;
for(i=0;i<A.r;i++)
{
for(j=0;j<A.c;j++)
{
out<<setw(6)<<A.data[i][j];
}
cout<<endl;
}
return out;
}
&
cout<<"A + B:"<<endl;
cout << (A + B) <<endl;
But after I changed the 2nd part into this,it just went well:
Matrix C;
cout<<"A + B:"<<endl;
cout << C <<endl;
I'm really confused what's wrong with the original code……actually it's part of the fixed framework of my programming homework,and I'm not allowed to change it. QAQ
Upvotes: 2
Views: 46
Reputation: 118340
(A + B)
The result of this addition operation is a temporary value.
ostream & operator<<(ostream &out, Matrix &A){
Temporaries do not bind, or convert, to mutable references. C++ does not work this way. They only bind to const
references. Just change the 2nd parameter of this operator<<
overload to const Matrix &
, and make any appropriate changes to the contents of this overload, as needed (it may be necessary to change Matrix
's mysterious "data" member's operator[]
overload as well, since it now gets invoked on a const
class instance).
Upvotes: 1