Aria
Aria

Reputation: 45

Ostream << and operator -= for classes?

I have 2 classes S and M. When I try to use

cout << s3 -= m2;

I get an error that sates:

no operator "-=" matches these operands operand types are: std::ostream -=

class S
{ 
public:
    S& operator-=(M& m)
    {
        //my code
        return *this;
    }
}

I tried with 3 parameters, including ostream, but -= has only 2. How can I fix this?

Upvotes: 1

Views: 83

Answers (2)

NathanOliver
NathanOliver

Reputation: 181027

This has to do with operator precedence. << has a higher precedence than -= so

cout<<s3-=m2;

is treated as

(cout << s3) -= m2;

and not

cout << (s3 -= m2);

You need to use the above form to get what you want.

Upvotes: 4

alexeykuzmin0
alexeykuzmin0

Reputation: 6440

You have no way to fix this. The operator precedence rules in c++ are fixed and cannot be overloaded.

The only possible solution is to change the using code. For example, if you write

cout << (s3 -= m2);

then your original code should work. Another option is splitting the line in two:

s3 -= m2;
cout << s3;

Upvotes: 0

Related Questions