Reputation: 492
Given the following code;
#include<iostream>
using namespace std;
int main(){
int number_1 = 3;
int result_1 = 10;
result_1 += number_1;
cout << ++result_1;
cout << result_1 += number_1;
}
The line cout << result_1 += number_1;
giving me an error.
no match for 'operator+=' (operand types are 'std::basic_ostream' and 'int')
On the other hand, the cout << ++result_1;
is running without any problems.
Can anyone please explain what is the error is for, what the cause is?
Upvotes: 3
Views: 7581
Reputation: 30624
Operator precedence.
The call is semantically equivalent to something like cout << result_1; cout += result;
- which is invalid.
Adding parentheses to the code (allowing the +=
computed before the <<
) as follows allows the code to compile;
cout << (result_1 += number_1);
On the error itself; the compiler cannot find an implementation of the operator +=
for the arguments provided - there isn't a standard one. This is because the cout << result_1
is evaluated before the operator +=
. From the above, this makes sense, but doesn't immediately indicate where the potential fix can be applied.
Upvotes: 2
Reputation: 173014
- Can anyone please explain what is the error is for, what the cause is?
According to Operator Precedence, operator<<
has higher precedence than operator+=
, so your code is equivalent as:
(cout << result_1) += number_1;
while cout << result_1
will return std::cout
(i.e. std::ostream&
) and then operator+=
is attempted to be called on std::ostream
and it doesn't exist. That's what the error message trying to tell you.
You could change it to:
cout << (result_1 += number_1) ;
or avoid such kind of confusing code fundamentally.
result_1 += number_1;
cout << result_1;
- On the other hand
cout << ++result_1;
is running with out any problem.
Beasuse operator++
has higher precedence than operator<<
. So it's equivalent as cout << (++result_1);
and would be fine.
Upvotes: 8
Reputation: 761
Read you commpiler error carefully. Everything is there :) .
The reason for error is operator precedence.
Compiler first executes cout << result_1
.
Then, it tries to execute something like this: cout += number_1
.
Does it have any sense?
To do what you intended change your line:
cout << (result_1 += number_1);
I strongly recommend reading this: http://en.cppreference.com/w/cpp/language/operator_precedence
Upvotes: 2
Reputation: 238441
If you take a look at the operator precedence rules, you'll find that the statement is equivalent to
(cout << result_1) += number_1 ;
The operator<<
returns the std::cout
. And there exists no std::ostream::operator+=(int)
.
Solution: Use parenthesis to express the intended order of operations.
On the other hand cout << ++result_1; is running with out any problem
As one would expect. Study the precedence of operators.
Upvotes: 2