//overloading + operator static member (+) (a : Complex, b: Complex) = Complex(a.x + b.x, a.y + b.y)上述函數(shù)為用戶定義的類Complex實(shí)現(xiàn)了加法運(yùn)算符(+)。 它添加兩個對象的屬性,并返回結(jié)果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())
當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出
7 5 4.2 3.1 11.2 8.1 2.8 1.9
更多建議: