using System;
class TwoDimension {
int x, y;
public TwoDimension() {
x = y = 0;
}
public TwoDimension(int i, int j) {
x = i;
y = j;
}
// Overload binary +.
public static TwoDimension operator +(TwoDimension op1, TwoDimension op2)
{
TwoDimension result = new TwoDimension();
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
return result;
}
// Overload binary -.
public static TwoDimension operator -(TwoDimension op1, TwoDimension op2)
{
TwoDimension result = new TwoDimension();
/* Notice the order of the operands. op1 is the left
operand and op2 is the right. */
result.x = op1.x - op2.x;
result.y = op1.y - op2.y;
return result;
}
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 + b; // add a and b together
Console.Write("Result of a + b: ");
c.show();
Console.WriteLine();
c = a + b + c; // add a, b and c together
Console.Write("Result of a + b + c: ");
c.show();
Console.WriteLine();
c = c - a; // subtract a
Console.Write("Result of c - a: ");
c.show();
Console.WriteLine();
c = c - b; // subtract b
Console.Write("Result of c - b: ");
c.show();
Console.WriteLine();
}
}
|