Overload unary - and ++
using System;
class TwoDimension {
int x, y;
public TwoDimension() {
x = y = 0;
}
public TwoDimension(int i, int j) {
x = i;
y = j;
}
// Overload unary -.
public static TwoDimension operator -(TwoDimension op)
{
TwoDimension result = new TwoDimension();
result.x = -op.x;
result.y = -op.y;
return result;
}
// Overload unary ++.
public static TwoDimension operator ++(TwoDimension op)
{
// for ++, modify argument
op.x++;
op.y++;
return op;
}
// Show X, Y
public void show()
{
Console.WriteLine(x + ", " + y);
}
}
class MainClass {
public static void Main() {
TwoDimension a = new TwoDimension(1, 2);
TwoDimension b = new TwoDimension(10, 10);
TwoDimension c = new TwoDimension();
Console.Write("Here is a: ");
a.show();
Console.WriteLine();
Console.Write("Here is b: ");
b.show();
Console.WriteLine();
c = -a; // assign -a to c
Console.Write("Result of -a: ");
c.show();
Console.WriteLine();
a++; // increment a
Console.Write("Result of a++: ");
a.show();
}
}
Here is a: 1, 2
Here is b: 10, 10
Result of -a: -1, -2
Result of a++: 2, 3