没有与'operator + ='匹配的内容(操作数类型为'std :: basic_ostream< char>'和'int') [英] no match for 'operator+=' (operand types are 'std::basic_ostream<char>' and 'int')
问题描述
给出以下代码;
#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;
}
行 cout<<result_1 + = number_1;
给我一个错误.
与'operator + ='不匹配(操作数类型为'std :: basic_ostream'和'int')
no match for 'operator+=' (operand types are 'std::basic_ostream' and 'int')
另一方面, cout<<++ result_1;
正在运行,没有任何问题.
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?
推荐答案
- 谁能解释这个错误是什么原因,是什么原因?
根据运算符优先级, operator<<
的优先级高于 operator + =
,因此您的代码等效于:
According to Operator Precedence, operator<<
has higher precedence than operator+=
, so your code is equivalent as:
(cout << result_1) += number_1;
而 cout<<result_1
将返回 std :: cout
(即 std :: ostream&
),然后尝试调用 operator + =
std :: ostream
,它不存在.这就是错误消息试图告诉您的内容.
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.
您可以将其更改为:
cout << (result_1 += number_1) ;
或者从根本上避免这种混淆代码.
or avoid such kind of confusing code fundamentally.
result_1 += number_1;
cout << result_1;
- 另一方面,
cout<<++ result_1;
正常运行.
因为 operator ++
的优先级高于 operator<<
.因此,它等效于 cout<<(++ result_1);
,就可以了.
Beasuse operator++
has higher precedence than operator<<
. So it's equivalent as cout << (++result_1);
and would be fine.
这篇关于没有与'operator + ='匹配的内容(操作数类型为'std :: basic_ostream< char>'和'int')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!