だらだらやるよ。

こげつのIT技術メモ

実際に演算子のオーバーロードを書いてみた。

演算子オーバーロードした場合、優先度はどうなるか?を実践。

ただintをラップしただけのクラスを用意

public class ExInt {
	int _n;

	public int N {
		get { return _n; }
		set { _n = value; }
	}
	public ExInt(int n) {
		_n = n;
	}
	public static ExInt operator +(ExInt a,ExInt b) {
		Console.WriteLine("plus");
		return new ExInt(a._n + b._n);
	}
	public static ExInt operator *(ExInt a,ExInt b) {
		Console.WriteLine("multiplication");
		return new ExInt(a._n * b._n);
	}
}

計算させてみる

static void Main() {
	ExInt ei1 = new ExInt(4);
	ExInt ei2 = new ExInt(3);
	ExInt ei3 = new ExInt(2);
	ExInt fin = ei1 + ei2 * ei3;
	Console.WriteLine("fin1:"+fin.N.ToString());
	int i1 = 4;
	int i2 = 3;
	int i3 = 2;
	int finInt = i1 + i2 * i3;
	Console.WriteLine("fin2:"+finInt);
}

で、結果

multiplication
plus
fin1:10
fin2:10

一緒ですね。
もし演算子オーバーロードで、色々な処理をさせていた場合に、実行順序で混乱しそうです。
いや、そもそも演算子にはそれ以上の仕事をさせるのは良くないから別にいっか・・・