C++中+=和=+的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19426268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:48:36  来源:igfitidea点击:

Difference between += and =+ in C++

c++operators

提问by spurra

While programming in C++, I often confuse both "+=" and "=+", the former being the operator I actually mean. Visual Studio seems to accept both, yet they behave differently and is a source for a lot of my bugs. I know that a += b is semantically equivalent to a = a+b, but what does "=+" do?

在用 C++ 编程时,我经常混淆“+=”和“=+”,前者是我真正指的运算符。Visual Studio 似乎接受两者,但它们的行为不同,并且是我的许多错误的来源。我知道 a += b 在语义上等同于 a = a+b,但是“=+”有什么作用呢?

回答by Daniel A. White

=+is really = +(assignment and the unary +operators).

=+是真的= +(赋值和一元运算+符)。

In order to help you remember +=, remember that it does addition first, then assignment. Of course that depends on the actual implementation, but it should be for the primitives.

为了帮助你记住+=,记住它是先加法,后赋值。当然,这取决于实际的实现,但它应该用于原语。

回答by Ivan Ishchenko

a =+ bmeans a = +bmeans a = b

a =+ b手段a = +b手段a = b

回答by Abdelrahman

if you see =the first , it means you re-declare your variable value , but if you face +the first it means that you order the compiler to increment the value of the variable , keep it in you mind

如果您看到=第一个,则意味着您重新声明了变量值,但是如果您遇到+第一个,则意味着您命令编译器增加变量的值,请记住它

int x=20 ;
x=+10 ;
cout<< x <<endl ; // x  = 10


x+=10 ;
cout<< x<<endl ; // x= 10+10 = 20