2012-03-29 3 views
2

아래 코드를 제시했습니다. 오버로드 된 접미사 연산자를 오버로드하면 컴파일러에서 오류가 발생합니다. 오버로드 된 접두사 연산자에서 잘 작동합니다. 오류오버로드 된 접미어 증가/감소 연산자에서 ostream 연산자 오버로드

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

답변

6

귀하의 operator<< const를 참조하여 Digit 매개 변수를 사용한다 : Digit::operator++(int) 임시 객체가 될 수 없습니다 반환하기 때문에

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

이 여기에 필요 비 const 참조를 취하는 함수로 전달됩니다.

+0

+1 그랬습니다! 나는 대부분의 C++ 자습서가 연산자 오버로딩을 언급하지 않는다는 것에 놀랐다. – enthusiasticgeek

+0

Hrm, 어쩌면 우리는 좀 더 나은 자습서를 작성해야 할 것입니다 :-) 당신이 그것을 고칠 의도가 없다면 엄지의 좋은 규칙이 있습니다. – bstamour

+0

나는 초보자/중급 수준의 프로그래머에게 오류가 있거나 "선생님/부인"과 같은 제안으로 합리적인 컴파일러를 좋아하지 않을 것입니다. const 한정자를 잊어 버렸습니까? " 부당한 복잡성의 일부 혼란보다는 (다행스럽게도이 경우에는 그렇지 않다). 바라기를 우리는 앞으로 그들을 볼 것입니다. :) – enthusiasticgeek