Operator overloading problems C++ -


i have polynomial class , have overloaded +,-, , * operators, << operator. seems work fine until try output expression such poly1+poly2 rather single polynomial object.

here addition operator code:

polynomial operator+ (const polynomial& poly1, const polynomial& poly2){     vector<int> final_coeffs;      if (poly1.degree()>poly2.degree())     {         (int i=0; i<=poly2.degree(); i++)             final_coeffs.push_back(poly2.coefficient(i) + poly1.coefficient(i));         (int i=poly2.degree()+1; i<=poly1.degree(); i++)             final_coeffs.push_back(poly1.coefficient(i));     }      else     {         (int i=0; i<=poly1.degree(); i++)             final_coeffs.push_back(poly1.coefficient(i) + poly2.coefficient(i));         (int i=poly1.degree()+1; i<=poly2.degree(); i++)             final_coeffs.push_back(poly2.coefficient(i));     }      return polynomial(final_coeffs); } 

and here << operator code (i have correctly working print member function):

ostream& operator<< (ostream& out, polynomial& poly){     poly.print();     return out; } 

the problem arises when try in main:

cout << poly1+poly2; 

but works fine if do:

cout << poly1; 

the error message says: invalid operands binary expression ('ofstream' (aka 'basic_ofstream') , ('polynomial')

and specific function should using: candidate function not viable: expects l-value 2nd argument

thank you!

you need:

ostream& operator<< (ostream& out, polynomial const& poly) { 

this because temporary object cannot bound non-const reference.

note means must make polynomial::print() function const.


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -