在重载I/O运算符内部重载增量运算符时出错

Error while overloading increment operator inside overloaded I/O operator

本文关键字:重载 运算符 出错 内部      更新时间:2023-10-16

我是OOPS概念的初学者。我现在正在处理操作员过载问题。当我在cout中使用重载的增量运算符时,我遇到了错误no match for operator<<。当我从cout中删除重载的增量时,它工作得很好。从逻辑上讲,我不觉得代码有什么问题。不过,我不知道为什么我会出错?下面是我的代码,以便更好地理解这个问题。

#include <iostream>
using namespace std;
class Digit
{
private:
    int digit;
public:
    Digit(int n)
    {
        digit = n;
    }
    Digit& operator++();
    Digit operator++(int); //overloaded postfix increment. Dummy argument used
    Digit& operator--();
    Digit operator--(int); //overloaded postfix decrement. Dummy argument used
    friend ostream& operator<<(ostream& out, Digit& x); //overloaded << prototype
    int GetDigit()
    {
        return digit;
    }
};
Digit Digit::operator++(int)
{
    //Create a temporary object with a variable
    Digit temp(digit);
    //Use prefix operator to increment this Digit
    ++(*this);
    return temp; //return temporary result
}
Digit& Digit::operator++()
{
    if (digit==9)
        digit = 0;
    else
        ++digit;
    return *this;
}
Digit Digit::operator--(int)
{
    //Create a temporary object with a variable
    Digit temp(digit);
    //Use prefix operator to increment this Digit
    --(*this);
    return temp; //return temporary result
}
Digit& Digit::operator--()
{
    if (digit==0)
        digit = 9;
    else
        --digit;
    return *this;
}
int main()
{
    using namespace std;
    Digit n(9);
    Digit x(0);

    cout << n++ << endl;
    cout << x-- << endl;
    return 0;
}
ostream& operator<<(ostream& out, Digit& x)
{
    out << x.digit;
    return out;
}

main()内部的线路cout << n++ << endl; cout << x-- << endl;导致错误。

这是因为后缀运算符通过值返回,如果不保存该值,则会有一个临时的,并且非常量引用无法绑定到临时引用。

简单的修复方法是让您的输出操作符通过const引用接受Digit参数:

ostream& operator<<(ostream& out, Digit const& x)
//                                      ^^^^^