0

I am a beginner to OOPS concept. I am working on Operator overloading now. I run into the error no match for operator<<when I use an overloaded increment operator inside cout. It works fine when I remove the overloaded increment from cout. Logically, I don't feel like anything wrong with the code. Still, I do not know why I get the error? Below is my code for better understanding of the issue.

#include <iostream>

using namespace std;
class Digit
{
private:
    int digit;

public:
    Digit(int n)
    {
        digit = n;
    }

    Digit& operator++();
    Digit operator++(int); //overloaded postfix increment. Dummy argument used
    Digit& operator--();
    Digit operator--(int); //overloaded postfix decrement. Dummy argument used

    friend ostream& operator<<(ostream& out, Digit& x); //overloaded << prototype

    int GetDigit()
    {
        return digit;
    }
};

Digit Digit::operator++(int)
{
    //Create a temporary object with a variable
    Digit temp(digit);

    //Use prefix operator to increment this Digit
    ++(*this);

    return temp; //return temporary result
}

Digit& Digit::operator++()
{
    if (digit==9)
        digit = 0;
    else
        ++digit;

    return *this;
}

Digit Digit::operator--(int)
{
    //Create a temporary object with a variable
    Digit temp(digit);

    //Use prefix operator to increment this Digit
    --(*this);

    return temp; //return temporary result
}

Digit& Digit::operator--()
{
    if (digit==0)
        digit = 9;
    else
        --digit;

    return *this;
}

int main()
{
    using namespace std;

    Digit n(9);
    Digit x(0);


    cout << n++ << endl;
    cout << x-- << endl;

    return 0;
}

ostream& operator<<(ostream& out, Digit& x)
{
    out << x.digit;

    return out;
}

The lines cout << n++ << endl; cout << x-- << endl;inside main() causes the error.

Kiran C K
  • 67
  • 7

1 Answers1

1

It's because the postfix operators return by value, and if you don't save that value you will have a temporary, and non-const references can't bind to temporaries.

Simple fix is to have your output operator take the Digit argument by const reference:

ostream& operator<<(ostream& out, Digit const& x)
//                                      ^^^^^
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621