+ = C ++中的运算符 [英] += Operator in C++
问题描述
有人请告诉我下面的代码添加两个变量的数据类型 int
之间的区别。我想知道哪一个更好。
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.
代码A:
sum = sum + value;
代码B :
sum += value;
我们通常喜欢 ++
code> + = 1 。还有什么特别的原因吗?
We usually prefer ++
operator over += 1
. Is there any specific reason behind that as well ?
我想知道上述代码之间的区别,相对于约定或效率水平。
推荐答案
someVar ++
运算符与 someVar + = 1
相同,还有其他东西。
While the end result of the e.g. someVar++
operator is the same as someVar += 1
there are other things playing in as well.
我们使用一个简单的语句,例如
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 arithmetic using those operators.
foo += 1;
和
foo = foo + 1;
对于基本类型没有什么不同(例如 int
或 float
)或指针类型,但是如果 foo
是一个操作符重载的对象,会有很大的区别。
there's no different for primitive types (like int
or float
) or pointer types, but there's a very big difference if foo
is an object with operator overloading. Then
foo += 1;
等于
foo.operator+=(1);
while
foo = foo + 1;
等于
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).
这篇关于+ = C ++中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!