質問

This is a dumb question but I'm stumped. Are the following two C++ statements identical?

regWages = regPay + overTime;
regPay + overTime = regWages;
役に立ちましたか?

解決

No. One is valid, the other isn't. (Maybe.*)

You can generally only assign to lvalues, which are, tautologically, things you can assign to. The result of an arithmetic expression usually isn't something you can assign to.

More simply: a = 1 + 2 is OK, but 1 + 2 = a is not. You can give a a value, but you cannot give the result of an addition of integers a value.

Assignment in C++ is a state change. It is very different from the mathematical concept of "equations". An assignment in C++ is more like a definition in mathematics, but unlike in maths you can reassign values to existing objects.

*) Operator overloading complicates the picture a bit.

他のヒント

To solve your doubt, you should understand ome import concept: Lvalues and Rvalues

In your code, regWages = regPay + overTime; is right, because if the variable regWages is Lvalues, it is a non-temporary object and you can do = operation.

regPay + overTime = regWages; is wrong, because of the result of regPay + overTime is Rvalues, just a temporary variable, you can't do = operation.

It is funny but the both operators can be valid depending of the type definition of the objects.

regWages = regPay + overTime;
regPay + overTime = regWages;

However semantically they are different, The assignment operator is not symmetric.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top