📜  F#-运算符重载

📅  最后修改于: 2020-11-21 07:00:38             🧑  作者: Mango


您可以重新定义或重载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