Tips - Visual C#

【TOP】

演算子をオーバーロードする
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; } // Xプロパティ public double X { get { return this._x; } set { this._x = value; } } // Yプロパティ public double Y { get { return this._y; } set { this._y = value; } } // 2点の距離を算出 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); } // Equalsメソッドのオーバーライド(念のため) 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); // Equalsメソッドの使用 Point e = new Point(1.2d, 0.3d); Console.Write("\nPoint a equals Point e ? "); Console.WriteLine("{0}", a.Equals(e)); // Point a と原点との距離 Console.Write("\nPoint a と原点との距離 = "); Console.WriteLine("{0:F3}", a.CalcDistance(new Point(0, 0))); // Point a と Point b の距離 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
【戻る】