【问题标题】:Error while overloading increment operator inside overloaded I/O operator在重载的 I/O 运算符中重载增量运算符时出错
【发布时间】:2016-03-17 07:32:44
【问题描述】:

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

cout &lt;&lt; n++ &lt;&lt; endl; cout &lt;&lt; x-- &lt;&lt; endl;inside main() 导致错误。

【问题讨论】:

    标签: c++ class operator-overloading post-increment friend-function


    【解决方案1】:

    这是因为后缀运算符返回按值,如果你不保存那个值你会有一个临时的,并且非常量引用不能绑定到临时。

    简单的解决方法是让您的输出运算符通过const 引用获取Digit 参数:

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

    【讨论】:

    • 当然我认为它依赖于编译器,因为 MS C++ 编译器将毫无问题地运行原始代码!
    • @EhsanKhodarahmi 非常量引用不能绑定到临时值,如果编译器允许,那就错了。
    • @Ehsan - 如果你有更新的 MS 编译器,它会警告你。如果你有一个非常旧的编译器,它根本就不能很好地遵循标准。
    • 我说的是 MS cpp 编译器 v12 (visual studio 2013),所以你们真的认为这是那个编译器的错误吗?
    • @EhsanKhodarahmi 在这种情况下这绝对是一个错误,因为根据 C++ 规范根本不允许这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2012-04-13
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多