enthusiasticgeek
enthusiasticgeek

Reputation: 2736

ostream operator overloading on an overloaded postfix increment/decrement operator

I have presented the code below. The compiler throws error when I overload an overloaded postfix operator. It works fine on an overloaded prefix operator. error

error: no match for ‘operator<<’ in ‘std::cout << cDigit.Digit::operator++(0)’

Code

#include <iostream>

using namespace std;

class Digit
{
private:
    int m_nDigit;
public:
    Digit(int nDigit=0)
    {
        m_nDigit = nDigit;
    }

    Digit& operator++(); // prefix
    Digit& operator--(); // prefix

    Digit operator++(int); // postfix
    Digit operator--(int); // postfix

    friend ostream& operator<< (ostream &out, Digit &digit);

    int GetDigit() const { return m_nDigit; }
};

Digit& Digit::operator++()
{
    // If our number is already at 9, wrap around to 0
    if (m_nDigit == 9)
        m_nDigit = 0;
    // otherwise just increment to next number
    else
        ++m_nDigit;

    return *this;
}

Digit& Digit::operator--()
{
    // If our number is already at 0, wrap around to 9
    if (m_nDigit == 0)
        m_nDigit = 9;
    // otherwise just decrement to next number
    else
        --m_nDigit;

    return *this;
}

Digit Digit::operator++(int)
{
    // Create a temporary variable with our current digit
    Digit cResult(m_nDigit);

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

    // return temporary result
    return cResult;       // return saved state
}

Digit Digit::operator--(int)
{
    // Create a temporary variable with our current digit
    Digit cResult(m_nDigit);

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

    // return temporary result
    return cResult;       // return saved state
}

ostream& operator<< (ostream &out, Digit &digit)
{
  out << digit.m_nDigit;
  return out;
}

int main()
{
    Digit cDigit(5);
    cout << ++cDigit << endl; // calls Digit::operator++();
    cout << --cDigit << endl; // calls Digit::operator--();
    cout << cDigit++ << endl; // calls Digit::operator++(int); //<- Error here??
 return 0;
}

Upvotes: 2

Views: 669

Answers (1)

interjay
interjay

Reputation: 110154

Your operator<< should take its Digit parameter by const reference:

ostream& operator<< (ostream &out, const Digit &digit)

This is needed here because Digit::operator++(int) returns a temporary object, which can't be passed to a function that takes a non-const reference.

Upvotes: 6

Related Questions