[讀書筆記 ]Stephens' C# Programming with Visual Studio 2010 24-Hour Trainer 第二十六章

  • 832
  • 0

閱讀Stephens' C#教材第二十六章筆記

 

Chapter 26 Overloading Operators.
 
本章將介紹運算子的overload,可以參考微軟網頁
 
前一章介紹方法的多載,C#中也可以讓運算子多載,讓原本的+及*有新的意義,例如可以將+號用在將Student物件與Course物件的相加。
 
但是作者指出雖然可以進行運算子的overload,但是要用在合理的地方,不是代表一定要讓運算子overload,兩個物品相加合理,但是讓兩個員工相加就會造成混淆。
 
可多載的一元運算子:+, -, !, ~, ++, --, (網頁還有 true, false)
   
可多載的二元運算子:+, -, *, /, %, &, |, ^, <<, >>
 
可多載的比較運算子:==, !=, >, <, >=, <=
 
既然是多載,當然還是要撰寫方法,在ComplexNumbers程式中,將-運算子覆寫的程式如下

        // Unary -.
        public static ComplexNumber operator -(ComplexNumber me)
        {
            return new ComplexNumber(-me.Real, -me.Imaginary);
        }
其中operator關鍵字必須在所要覆寫的運算子之前。
當覆寫一元運算子-(負號)運算子後
ComplexNumber a = new ComplexNumber(1,2)     // a值為 1+2i
執行
ComplexNumber minusA  = -a;       // minusA 值為 -1-2i
 
覆寫二元運算子跟一元運算子差不多,但是可能要用到兩個參數

        public static ComplexNumber operator -(ComplexNumber me, ComplexNumber other)
        {
            return new ComplexNumber(me.Real - other.Real, mej.Imaginary - other.Imaginary);
        }
 
TRY IT就是以ComplexNumber程式示範如果撰寫覆寫運算子的過程。