ostream运算符在重载的后缀增量/减量运算符上重载

ent*_*eek 2 c++ operator-overloading ostream postfix-operator

我已经提供了以下代码.当我重载一个重载的后缀运算符时,编译器抛出错误.它在重载的前缀运算符上工作正常.错误

error: no match for ‘operator<<’ in ‘std::cout << cDigit.Digit::operator++(0)’
Run Code Online (Sandbox Code Playgroud)

#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;
}
Run Code Online (Sandbox Code Playgroud)

int*_*jay 6

operator<<应该Digit通过const引用获取其参数:

ostream& operator<< (ostream &out, const Digit &digit)
Run Code Online (Sandbox Code Playgroud)

这是需要的,因为Digit::operator++(int)返回一个临时对象,该对象无法传递给采用非const引用的函数.