F# - 運算子過載



您可以重新定義或過載 F# 中大多數可用的內建運算子。因此,程式設計師也可以將運算子與使用者定義型別一起使用。

運算子是用括號括起來的特殊名稱的函式。它們必須定義為靜態類成員。與任何其他函式一樣,過載的運算子具有返回型別和引數列表。

以下示例顯示了複數上的 + 運算子:

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

上述函式實現了使用者定義類 Complex 的加法運算子 (+) 。它添加了兩個物件的屬性並返回結果 Complex 物件。

運算子過載的實現

下面的程式顯示了完整的實現:

//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())

編譯並執行程式後,將產生以下輸出:

7 5
4.2 3.1
11.2 8.1
2.8 1.9
廣告
© . All rights reserved.