F#運(yùn)算符重載

2018-12-16 13:58 更新

您可以重新定義或重載F#中提供的大多數(shù)內(nèi)置運(yùn)算符。 因此,程序員也可以使用具有用戶定義類型的運(yùn)算符。
運(yùn)算符是用括號(hào)括起來的特殊名稱的函數(shù)。 它們必須定義為靜態(tài)類成員。 與任何其他函數(shù)一樣,重載運(yùn)算符具有返回類型和參數(shù)列表。
以下示例顯示了復(fù)數(shù)上的+運(yùn)算符 

//overloading + operator
static member (+) (a : Complex, b: Complex) =
Complex(a.x + b.x, a.y + b.y)

上述函數(shù)為用戶定義的類Complex實(shí)現(xiàn)了加法運(yùn)算符(+)。 它添加兩個(gè)對(duì)象的屬性,并返回結(jié)果Complex對(duì)象。

執(zhí)行運(yùn)算符重載

以下程序顯示了完整的實(shí)現(xiàn) 

//implementing a complex class with +, and - operators
//overloaded
type Complex(x: float, y : float) =
   member this.x = x
   member this.y = y
   //overloading + operator
   static member (+) (a : Complex, b: Complex) =
      Complex(a.x + b.x, a.y + b.y)

   //overloading - operator
   static member (-) (a : Complex, b: Complex) =
      Complex(a.x - b.x, a.y - b.y)

   // overriding the ToString method
   override this.ToString() =
      this.x.ToString() + " " + this.y.ToString()

//Creating two complex numbers
let c1 = Complex(7.0, 5.0)
let c2 = Complex(4.2, 3.1)

// addition and subtraction using the
//overloaded operators
let c3 = c1 + c2
let c4 = c1 - c2

//printing the complex numbers
printfn "%s" (c1.ToString())
printfn "%s" (c2.ToString())
printfn "%s" (c3.ToString())
printfn "%s" (c4.ToString())

當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出 

7 5
4.2 3.1
11.2 8.1
2.8 1.9
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)