- F# 基礎教程
- F# - 首頁
- F# - 概述
- F# - 環境設定
- F# - 程式結構
- F# - 基本語法
- F# - 資料型別
- F# - 變數
- F# - 運算子
- F# - 決策
- F# - 迴圈
- F# - 函式
- F# - 字串
- F# - 可選項
- F# - 元組
- F# - 記錄
- F# - 列表
- F# - 序列
- F# - 集合
- F# - 對映
- F# - 判別聯合
- F# - 可變資料
- F# - 陣列
- F# - 可變列表
- F# - 可變字典
- F# - 基本I/O
- F# - 泛型
- F# - 委託
- F# - 列舉
- F# - 模式匹配
- F# - 異常處理
- F# - 類
- F# - 結構體
- F# - 運算子過載
- F# - 繼承
- F# - 介面
- F# - 事件
- F# - 模組
- F# - 名稱空間
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
廣告