Reputation: 13
I have a Polynomial class and I have overloaded the +,-, and * operators, as well as the << operator. It all seems to work fine until I try to output an expression such as poly1+poly2 rather than just a single Polynomial object.
Here is my addition operator code:
Polynomial operator+ (const Polynomial& poly1, const Polynomial& poly2){
vector<int> final_coeffs;
if (poly1.Degree()>poly2.Degree())
{
for (int i=0; i<=poly2.Degree(); i++)
final_coeffs.push_back(poly2.Coefficient(i) + poly1.Coefficient(i));
for (int i=poly2.Degree()+1; i<=poly1.Degree(); i++)
final_coeffs.push_back(poly1.Coefficient(i));
}
else
{
for (int i=0; i<=poly1.Degree(); i++)
final_coeffs.push_back(poly1.Coefficient(i) + poly2.Coefficient(i));
for (int i=poly1.Degree()+1; i<=poly2.Degree(); i++)
final_coeffs.push_back(poly2.Coefficient(i));
}
return Polynomial(final_coeffs);
}
And here is my << operator code (I already have a correctly working print member function):
ostream& operator<< (ostream& out, Polynomial& poly){
poly.print();
return out;
}
The problem arises when I try to do this in main:
cout << poly1+poly2;
But works fine if I just do:
cout << poly1;
The error message says: Invalid operands to binary expression ('ofstream' (aka 'basic_ofstream') and ('Polynomial')
And for the specific function it should be using: Candidate function not viable: expects an l-value for 2nd argument
Thank you!
Upvotes: 1
Views: 1863
Reputation: 141598
You need:
ostream& operator<< (ostream& out, Polynomial const& poly) {
This is because a temporary object cannot be bound to a non-const reference.
Note that this means you also must make the Polynomial::print()
function be const
.
Upvotes: 4