JSRUN 用代码说话

重载运算符

编辑教程

重载运算符

您可以重新定义或重载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
JSRUN闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
金额: 0
备注:
转账时请填写正确的金额和备注信息,到账由人工处理,可能需要较长时间
如有疑问请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟