0

I overloaded "<<" and it works fine, the same for "+=", but they won't work together. I don't get why, += returns a foo& object, just like "++" which works fine. I see that something like int x; cout<<x+=1; doesn't work too, but I don't think that explains why my code shouldn't work, after all it's pretty much the same as "++", it has the same type of return. Here is my code:

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

    foo& operator+=(const int& value)
    {
        x=x+value;

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

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

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


int main()
{

    foo A, B, C;

    cout<<B++;      /// works fine, prints 11 
    C+=20;
    cout<<C;       /// works fine, prints 30
    
    cout<<A+=99;   ///error: no match for 'operator+=' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'int')


    return 0;
}
  • 2
    `cout<<(A+=99);` – Quimby Mar 24 '21 at 15:48
  • It works now, but why do i need ()? –  Mar 24 '21 at 15:49
  • 1
    Your postfix operator ++ seems to be implemented semantically incorrectly. **works fine, prints 11** I expect it would print 10. – 273K Mar 24 '21 at 15:50
  • Only the postfix increment is incorrect. – sweenish Mar 24 '21 at 15:51
  • 2
    Without the brackets suggested by Quimby, you are attempting: `(cout << A) += 99`. – Adrian Mole Mar 24 '21 at 15:52
  • Your postfix increment is still incorrect. You can see a more correct implementation in [my answer](https://stackoverflow.com/a/66771132/6119582) to your previous and very similar question. – sweenish Mar 24 '21 at 15:54
  • 2
    See [operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) for more. Operator overloading can't change the behavior that `<<` binds more tightly than `+=`. – Nathan Pierson Mar 24 '21 at 15:55
  • @sweenish My bad, I have understood how it's done, i think i just reused an old code from yesterday, probably i didn't save the good one. Thank you! –  Mar 24 '21 at 15:59

0 Answers0