Tuesday, 15 July 2014

C++ operator overloading prefix/suffix -


I am learning operator overloading in C ++ The basic suffix is ​​the property of ++, in which the lower priority than the assignment operator is. For example, int i = 0, j = 0; I = J ++; Cout & lt; & Lt; I & lt; & Lt; J output will be 01. But when I surcharge on Postfix ++ this property is lost.

  # include & lt; Iostream & gt; using namespace std; Class V {Public: Int Week [2]; V (int a0, int a1) {vec [0] = a0; Vec [1] = a1; } V operator ++ (int dummy) {for (int i = 0; i & lt; 2; i ++) {++ vec [i]; } VV (vec [0], VCC [1]); Return vi; } V operator = (V other) {vec [0] = other.vec [0]; Vec [1] = other.vec [1]; Return * This; } Zero print () {cout & lt; & Lt; "(" & Lt;   

Output (0,0) (2,2) while I expected (0,0) (1,1).

Can you help me understand this is such, and there is a possibility to restore the original property?

print it (0, 0) (2,2) because your Operator ++ , unlike the underlying one, returns a copy of the V object on which it works then before it can grow first Instead,

When you surcharge the operator, it is completely under your control, so it is your responsibility that you behave like a related operator in this regard.

In this way you can rewrite your operator to achieve that goal:

  V operator ++ (int dummy) {VVEC [ 0], VCK [1]); Make a copy before / incrementing: we'll return it! For (int i = 0; i & lt; 2; i ++) {++ vec [i]; } Return V; // Now it is * not * * a copy of the increased V object, but there is a copy of the V object before moving! }   

Here is one.

No comments:

Post a Comment