I am trying to port some C# code to another language (C# is not my usual language).
I have a vector class (cpVect
) that overrides the '+' operator twice:
public static cpVect operator +(cpVect p1, cpVect p2)
{
return new cpVect(
p1.x + p2.x,
p1.y + p2.y
);
}
public static cpVect operator +(cpVect p1)
{
return new cpVect(
+p1.x,
+p1.y
);
}
I can see that a new instance of cpVect
is returned from both methods but I'm trying to figure out how one would call these methods in a code example (so I can make sure I'm porting them correctly). For instance, does the second method add p1 to the receiving cpVect?
v3 = v1 + v2 <-- does this call method one above?
v1 = v1 + v2 <-- does this call method two above?
Thanks
Both call the binary operator. The unary operator would be called if you only had one operand:
v3 = +v1;
The unary +
operator is rarely useful, to be honest - but it's mostly there for symmetry with the unary -
operator.
See more on this question at Stackoverflow