2012-03-29 96 views
2

我已经提供了下面的代码。当我重载一个重载的postfix操作符时,编译器会抛出错误。它可以在重载的前缀运算符上正常工作。错误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参数:

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

这是需要在这里,因为Digit::operator++(int)返回一个临时对象,它不能传递给一个带有非const引用的函数。

+0

+1就是这样!我很惊讶,大多数C++教程没有提到,而运算符重载。 – enthusiasticgeek 2012-03-29 15:21:46

+0

Hrm,也许我们需要编写一些更好的教程:-)一个很好的经验法则是,如果你没有修改它的意图,使它成为const。 – bstamour 2012-03-29 15:46:56

+0

我会喜欢更聪明的编译器,这对于新手/中级程序员来说是不太合理的,并且有错误和建议,比如“先生/女士你忘记了const限定符了吗?”而不是一些无理复杂的大杂烩(幸运的是在这种情况下并不多)。希望我们能在未来看到他们。 :) – enthusiasticgeek 2012-03-29 16:13:12