【问题标题】:ostream operator overloading on an overloaded postfix increment/decrement operatorostream 运算符在重载的后缀增量/减量运算符上重载
【发布时间】:2012-04-13 06:17:05
【问题描述】:

我已经提供了下面的代码。当我重载一个重载的后缀运算符时,编译器会抛出错误。它适用于重载的前缀运算符。错误

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

【问题讨论】:

    标签: c++ operator-overloading ostream postfix-operator


    【解决方案1】:

    您的 operator&lt;&lt; 应该通过 const 引用获取其 Digit 参数:

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

    这里需要这样做,因为Digit::operator++(int) 返回一个临时对象,该对象不能传递给采用非常量引用的函数。

    【讨论】:

    • +1 是的,就是这样!我很惊讶大多数 C++ 教程在运算符重载时都没有提到这一点。
    • Hrm,也许我们需要写一些更好的教程 :-) 一个好的经验法则是,如果您不打算修改它,请将其设为 const。
    • 我喜欢更聪明的编译器,它对新手/中级程序员来说不太合理,会出现错误和建议,比如“先生/女士,你忘记了 const 限定符吗?”而不是一些毫无根据的复杂性的大杂烩(幸运的是在这种情况下没有那么多)。希望我们将来能见到他们。 :)
    猜你喜欢
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多