C++ 中的 += 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34465848/
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-28 14:22:44  来源:igfitidea点击:

+= Operator in C++

c++operators

提问by Itban Saeed

Someone please tell me the difference between the following codes which add two variables of datatype int. I want to know which one is better.

有人请告诉我添加两个数据类型变量的以下代码之间的区别int。我想知道哪个更好。

Code A:

代码 A:

sum = sum + value;

Code B:

代码 B:

sum += value;

We usually prefer ++operator over += 1. Is there any specific reason behind that as well ?

我们通常更喜欢++运算符而不是+= 1. 这背后有什么具体原因吗?

I want to know the difference between the above codes with respect to the conventions or efficiency level. Which one is recommended ?

我想知道上述代码在约定或效率级别方面的区别。推荐哪一款?

回答by Some programmer dude

While the end result of the e.g. someVar++operator is the same as someVar += 1there are other things playing in as well.

虽然 egsomeVar++运算符的最终结果与someVar += 1其他东西相同。

Lets take a simple statement like

让我们做一个简单的陈述,比如

foo = bar++;

It's actually equivalent (but not equal) to

它实际上相当于(但不等于)

temp = bar;
bar += 1;
foo = temp;

As for the prefix and suffix increment or decrement operators, they have different operator precedence, which will affect things like pointer arithmeticusing those operators.

至于前缀和后缀递增或递减运算符,它们具有不同的运算符优先级,这将影响使用这些运算符的指针算术等内容。



As for the difference between

至于两者的区别

foo += 1;

and

foo = foo + 1;

there's no different for primitive types (like intor float) or pointer types, but there's a very big difference if foois an object with operator overloading. Then

原始类型(如intor float)或指针类型没有什么不同,但是如果foo是带有运算符重载的对象,则有很大的不同。然后

foo += 1;

is equal to

等于

foo.operator+=(1);

while

尽管

foo = foo + 1;

is equal to

等于

temp = foo.operator+(1);
foo.operator=(temp);

Semantically a very big difference. Practically too, especially if any of the operator overload functions have side-effects, or if the copy-constructor or destructor have some side-effects (or you forget the rules of three, five or zero).

语义上有很大的不同。实际上也是如此,特别是如果任何运算符重载函数有副作用,或者如果复制构造函数或析构函数有一些副作用(或者你忘记了三、五或零的规则)。

回答by Paul Evans

One calls operators =and +the later calls operator +=.

一个调用 operator =+后者调用 operator +=

operators ++and +=are preferred because of readability - most programmers know what they mean.

运算符+++=因为可读性而受到青睐——大多数程序员都知道它们的意思。

On the other hand most modern compilers will generate the same code for += 1as ++and +/=as +=for builtin types;

另一方面,大多数现代编译器将为+= 1as+++/ =as生成与+=内置类型相同的代码;

But for user defined classs, the actual operators will be called and it's up to the implementer of those classs to make sense of it all. In these cases ++and +=can be optimal.

但是对于用户定义的classs,将调用实际的运算符,由这些classs的实现者来理解这一切。在这些情况下+++=可以是最佳的。

回答by Pétur Ingi Egilsson

cout << sum++;Would print out the value of sum before it was incremented. Also, depending on what you are doing, you can overwrite the operators +=and +.

cout << sum++;将在 sum 增加之前打印出 sum 的值。此外,根据您在做什么,您可以覆盖运算符+=+.

回答by Grantly

When you minimize code, you reduce the chance of an error (a typographical error or a logical error).

当您最小化代码时,您会减少出现错误(印刷错误或逻辑错误)的机会。

By using

通过使用

sum += value;

you reduce the chance - ever so slightly - of an error while typing

你减少了打字时出错的机会 - 非常轻微 -

sum = sum + value;

The same with value++;

value++;

value += 1;

could be more easily confused with

可能更容易与

value += l;where l is a variable....

value += l;其中 l 是一个变量....

Its more about consistency that it is about right or wrong, but reducing code is a major bonus for maintainability.

它更多的是关于一致性,它关乎对或错,但减少代码是可维护性的主要奖励。

Care must be taken with precendence of operators however, in complex statements.

但是,在复杂语句中,必须注意运算符的优先级。

回答by Bob Jarvis - Reinstate Monica

In the case shown there's no particular reason to prefer one method of incrementing the value over another except perhaps for readability purposes. In this case I think I'd prefer sum += valueover sum = sum + valueas it's a bit briefer and (I think) clearer, but YMMV on that.

在所示的情况下,除了可能出于可读性目的之外,没有特别的理由更喜欢一种增加值的方法而不是另一种方法。在这种情况下,我认为我更喜欢它sum += valuesum = sum + value因为它更简洁并且(我认为)更清晰,但是 YMMV 对此。

As far as prefering ++over += 1, (IMO again) ++is preferable when incrementing a value as part of an expression, e.g. sum += array[index++]- but if the entire point of what's being done is adding one to a value I'd prefer index += 1. But let's face it, a great deal of this is personal preference and spur-of-the-moment choice. I always try to write what I think, at that moment, is the simplest and clearest code possible - but I must admit that when I go back and read some of my own code later I have more "What was I thinkin'?!?" moments than I'd care to admit to. :-)

至于prefering+++= 1,(IMO再次)++增加值作为表达式,如部分时最好sum += array[index++]-但如果得到了些什么,整个点增加一个到一个值我喜欢index += 1。但让我们面对现实,这在很大程度上是个人喜好和一时冲动的选择。我总是试着写出我当时认为最简单、最清晰的代码——但我必须承认,当我回去阅读我自己的一些代码时,我有更多的“我在想什么?!? ” 比我愿意承认的时刻。:-)

YMMV.

天啊。

Best of luck.

祝你好运。

回答by James Wu

Code A and B do the same thing. The advantage to using Code B is that it's quicker to type and easier to read.

代码 A 和 B 做同样的事情。使用代码 B 的优点是键入速度更快且更易于阅读。

As for using the ++operator over += 1, again it is for readability. Although there is a difference between foo++and ++foo. The former is read first and then incremented, while the latter is incremented first and then read from.

至于使用++运算符 over += 1,再次是为了可读性。虽然foo++和之间有区别++foo。前者先读后递增,后者先递增后读。

回答by Sazzad Hissain Khan

A compound assignment expression of the form E1 op= E2is equivalent to E1 = (T)((E1) op (E2)), where Tis the type of E1, except that E1is evaluated only once.

形式的复合赋值表达式E1 op= E2等价于E1 = (T)((E1) op (E2)),其中T是 的类型E1,只是E1只计算一次。

An example cited from Java's +=, -=, *=, /= compound assignment operators

引用自Java 的 +=、-=、*=、/= 复合赋值运算符的示例

[...] the following code is correct:

[...] 以下代码是正确的:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

并导致 x 的值为 7,因为它等价于:

short x = 3;
x = (short)(x + 4.6);

回答by Saleem Ullah

They both are same up to that, both can be used for incrementing the value of a variable (stored in it).

它们都是相同的,都可以用于增加变量的值(存储在其中)。

x++will increment the value of xby one (1) every run time.

x++将在x每次运行时将 的值增加一 (1)。

+=adds right operand to the left operand and stores the result in left operand. Something like following: C += Ais just same as C = C + A

+=将右操作数添加到左操作数并将结果存储在左操作数中。类似于以下内容: C += AC = C + A

The difference between both ++and +=is that the first can increment by one (1) only, while +=can be used to increment more than one in just one line.

二者之间的差+++=是通过一(1)在第一罐增量而已,而+=可以使用在仅一个线递增一个以上。

e.g:

例如:

x += 1; // will increment by 1 every run time
x += 4; // will increment by 4 every run time
x += 10; // will increment by 10 every run time

回答by washington

There is no difference between the two in terms of functionality. A += B actually means A = A + B. The first one is just a shorter way of writing the second.

两者在功能上没有区别。A += B 实际上意味着 A = A + B。第一个只是写第二个的更短的方式。

回答by washington

Its basically the same thing. Its both an operator.

它基本上是一样的。它既是运营商。

One of it calls =and +. And the other +=..

其中之一调用=+。而另一个+=..

So if you did value +=5. Value goes up by 5. += is better and more organized. And shortens your code whitch is better and more professional.

所以如果你确实价值+=5。值增加 5。+= 更好,更有条理。并缩短您的代码,使其更好更专业。