2

以下にコードを提示しました。オーバーロードされた後置演算子をオーバーロードすると、コンパイラがエラーをスローします。オーバーロードされたプレフィックス演算子で正常に機能します。エラー

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

コード

#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;
}
4

1 に答える 1

6

const参照によってパラメーターoperator<<を取得する必要があります。Digit

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

Digit::operator++(int)非 const 参照を取る関数に渡すことができない一時オブジェクトを返すため、ここでこれが必要です。

于 2012-03-29T15:08:38.310 に答える