2次元空間上の点を表すPointというクラスを考えます。
このクラスはX座標値を表す「X」というプロパティと、同じくY座標値を表す「Y」というプロパティ、
および座標値を表示するPrintメソッド、2点間の距離を求めるCalcDistanceメソッドを持つものとします。
ある2つのPointクラスのインスタンスA、Bについて、以下の定義をおこないます。
・加算(A + B) → X座標値:A.X + B.X、Y座標値:A.Y + B.Y を持つ点を表す
・減算(A - B) → X座標値:A.X - B.X、Y座標値:A.Y - B.Y を持つ点を表す
・同じ位置に存在する → A.X == B.X かつ A.Y == B.Y が成立する
これを実現するために演算子「+」「-」「==」「!=」をPointクラス内でオーバーロードします。
using System;
using System.Collections.Generic;
using System.Text;
namespace OverloadOperatorTest
{
public class Point
{
protected double _x;
protected double _y;
public Point(double x, double y)
{
this._x = x;
this._y = y;
}
public double X
{
get
{
return this._x;
}
set
{
this._x = value;
}
}
public double Y
{
get
{
return this._y;
}
set
{
this._y = value;
}
}
public double CalcDistance(Point target)
{
return Math.Sqrt(Math.Pow(this.X - target.X, 2) + Math.Pow(this.Y - target.Y, 2));
}
public void Print()
{
Console.WriteLine("({0:F2} , {1:F2})", this._x, this._y);
}
public static Point operator + (Point a, Point b)
{
return new Point(a.X + b.X, a.Y + b.Y);
}
public static Point operator - (Point a, Point b)
{
return new Point(a.X - b.X, a.Y - b.Y);
}
public static bool operator == (Point a, Point b)
{
if(a.X == b.X && a.Y == b.Y)
{
return true;
}
else
{
return false;
}
}
public static bool operator != (Point a, Point b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (!(obj is Point))
{
return false;
}
else
{
return this == (Point)obj;
}
}
}
class Program
{
static void Main()
{
Console.Write("Point a = ");
Point a = new Point(1.2d, 0.3d);
a.Print();
Console.Write("\nPoint b = ");
Point b = new Point(0.63d, 3.4d);
b.Print();
Console.Write("\nPoint c ( Point a + Point b) = ");
Point c = a + b;
c.Print();
Console.Write("\nPoint d ( Point a - Point b) = ");
Point d = a - b;
d.Print();
Console.Write("\nPoint c == Point d ? ");
Console.WriteLine(c == d);
Point e = new Point(1.2d, 0.3d);
Console.Write("\nPoint a equals Point e ? ");
Console.WriteLine("{0}", a.Equals(e));
Console.Write("\nPoint a と原点との距離 = ");
Console.WriteLine("{0:F3}", a.CalcDistance(new Point(0, 0)));
Console.Write("\nPoint a と Point b の距離 = ");
Console.WriteLine("{0:F3}", a.CalcDistance(b));
}
}
}
上のプログラムを実行すると以下のような結果となります。
Point a = (1.20 , 0.30)
Point b = (0.63 , 3.40)
Point c ( Point a + Point b) = (1.83 , 3.70)
Point d ( Point a - Point b) = (0.57 , -3.10)
Point c == Point d ? False
Point a equals Point e ? True
Point a と原点との距離 = 1.237
Point a と Point b の距離 = 3.152