为什么不超载“<<"和"++"一起工作? [英] Why don't overloaded "<<" and "++" work together?

查看:45
本文介绍了为什么不超载“<<"和"++"一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我对C ++和OOP还是很陌生,因此如果提出愚蠢的问题,请您谅解.因此,在这里,我重载了<<"和"++"(后缀和前缀),并且它们可以单独正常工作.但是当结合使用时,它们似乎不起作用.我不明白为什么,两个++都返回一个foo类型的对象,所以我认为<<"应该可以正常工作...

Firstly, i'm pretty new to C++ and OOP, so sorry if asking silly questions. So, here it is, I overloaded the "<<" and "++" (postfix and prefix) and they work fine alone. But they seem to not work when combined. I don't get why, both ++-s return a foo type object, so I thinked that "<<" should work fine...

#include <iostream>
using namespace std;

class foo
{
    int x;

 public:
    foo()
    {
        x=10;
    }
    
    foo(const foo& f1)
    {
        this->x=f1.x;
        cout<<"OK";      /// testing if it really works
    }

    foo operator ++ ()
    {
        ++x;
        return *this;
    }

    foo operator ++ (int)
    {
        x++;
        return *this;
    }

    
    friend istream& operator>>(istream& in, foo& S);
    friend ostream& operator<<(ostream& out, foo& S);
};

istream& operator>>(istream& in, foo& S)
    {
        in>>S.x;
        return in; 
    }

ostream& operator<<(ostream& out, foo& S)
    {
        out<<S.x;
        return out;
    }
int main()
{

    foo A, B, C;

    cout<<A;
    //cout<<++A;       //error: cannot bind non-const lvalue reference of type 'foo&' to an rvalue of type 'foo'
    //cout<<A++;       //error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'foo')




    return 0;
}

推荐答案

您的流输出重载应将您的 foo 引用作为 const .毕竟,他们不应该修改传入的 foo :

Your stream output overload should take your foo references as const. After all, they shouldn't be modifying the foo's passed in:

friend istream& operator<<(istream& in, const foo& S);

非常量引用参数(例如您的 foo& S )必须具有一个传递给它的l值.由于您的增量运算符返回一个r值,因此您会看到编译器错误(确切地说就是这样).为了能够同时获取l值和r值,您需要在上面对const-reference参数进行更改.

A non-const reference parameter (like your foo& S), must have an l-value passed to it. Since your increment operator returns an r-value, you're seeing the compiler error (which says exactly this). To be able to take both l and r-values, you need to make the change to a const-reference parameter above.

此外,您的前缀增量运算符应按引用返回:

In addition, your prefix increment operator should return by reference:

foo& operator ++ ()
{
    ++x;
    return *this;
}

有关重载的基本规则和惯用语的更多信息,请阅读此处: https://stackoverflow.com/a/4421719/2602718

For more on the basic rules and idioms for overloading, read here: https://stackoverflow.com/a/4421719/2602718

这篇关于为什么不超载“&lt;&lt;"和"++"一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆