0

I'm trying to overload my << operator, but I want to use a helper function because I'm working with a tree, and that way my helper fn. can be recursive. But when I try to call the helper from the operator function I'm getting this no matching function call error.

std::ostream& operator<<(std::ostream& out, const Polynomial &rhs)
{
    Polynomial::Node *p = rhs.root;
    rhs.printPoly(p, out);
    return out;
}


void Polynomial::printPoly(Node* p, std::ostream &out)
{
    if(p == nullptr)
        return;
    printPoly(p->left, out);
    out << p->item->coeff() << "x^" << p->item->x();
    printPoly(p->right, out);
}

and in the .h file

friend std::ostream& operator<<(std::ostream& out, const Polynomial& rhs);

Oh and here's the error:

no matching function for call to 'Polynomial::printPoly(Polynomial::Node*&, std::ostream&) const'

Scuba Steve
  • 1,541
  • 1
  • 19
  • 47

2 Answers2

2

Add const to the end of your function declaration:

void Polynomial::printPoly(Node* p, std::ostream &out) const
{
    ...
}

This extra const tells the compiler that you won't be modifying the Polynomial object in the printPoly method.

godel9
  • 7,340
  • 1
  • 33
  • 53
0

Ah I just ditched the const in the declaration of Polynomial &rhs, and it seems happy.

Scuba Steve
  • 1,541
  • 1
  • 19
  • 47
  • You actually want that `const`, since you're not modifying the object in the function. Adding `const` qualifiers where appropriate helps avoid undesired side-effects and helps with compiler optimization. – godel9 Nov 17 '13 at 20:12