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

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

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

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

最佳答案

你的 operator<<应该取它的Digit常量引用的参数:

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

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

关于c++ - ostream 运算符在重载的后缀增量/减量运算符上重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9928121/

相关文章:

c++ - 我可以扔流吗?

c++ - ostream.h : No such file or directory

c++ - 3点的平面方程式未返回正确值

C++ 映射集混合

C++ 运算符 "="重载 - 使 lhs 上 vector ​​中的所有值等于 rhs 上的 double 值

c++ - 添加两个矩阵打印一列垃圾数据c++

c++ - ostream 是如何管理内存的?

c++ - Xcode 使用 C++ 在控制台中不显示任何内容

无法在 Visual Studio 2012 中编译但在 Visual Studio 2005 中运行良好的 C++ 类型转换运算符代码

c++ STL容器存储了一个重载operator =的类