Operator Overloading.
Operator Overloads let redefine the meaning of particular operators.
The over-ridable operators are;
Mathematical Operators: + - * / \ ^ Mod
Comparison Operators: < > = <> <= >= IsTrue IsFalse
Logical Operators: And Or Not Xor
CType Operators:
Narrowing CType
Widening CType
Shift Operators: >> <<
String Operator: &
Example: Angle Class
Suppose we define a class to contain an angle in Degrees, with a value (0<= a <360).
Now we want to calculate what the result of result of the following equation.
A=90°
B=45°
C=270°
T=(A-B)+C
Public Class Angle
Protected mAngle As Decimal = 0
Public Sub New(Optional ByVal Angle As Decimal = 0)
Me.Angle = Angle
End Sub
Public Property Angle() As Decimal
Get
Return mAngle
End Get
Set(ByVal value As Decimal)
mAngle = value
Normalise()
End Set
End Property
Private Sub Normalise()
mAngle = mAngle Mod 360
End Sub
Shared Function Add(ByVal aA As Angle, ByVal aB As Angle) As Angle
Return New Angle(Angle:=aA.Angle + aB.Angle)
End Function
Shared Function Subtract(ByVal aA As Angle, ByVal aB As Angle) As Angle
Return New Angle(Angle:=aA.Angle - aB.Angle)
End Function
Public Overrides Function ToString() As String
Return String.Format("{0}°", mAngle)
End Function
End Class
So with above version of the angle class (without operator overloads) to implement the equation we would have to use function calls.
Dim T = Angle.Add(Angle.Subtract( A , B ) , C )
Note that we have to write the addition first than the subtraction. Plus it is getting rather hard to tell the meaning of the code. Imagine if the equation was longer.
Using Operator Overloads
To enable use to write the equation as written we need to add in the operator overloads to the Angle class.
Public Class Angle
Protected mAngle As Decimal = 0
Public Sub New(Optional ByVal Angle As Decimal = 0)
Me.Angle = Angle
End Sub
Public Property Angle() As Decimal
Get
Return mAngle
End Get
Set(ByVal value As Decimal)
mAngle = value
Normalise()
End Set
End Property
Private Sub Normalise()
mAngle = mAngle Mod 360
End Sub
Shared Operator +(ByVal aA As Angle, ByVal aB As Angle) As Angle
Return New Angle(Angle:=aA.Angle + aB.Angle)
End Operator
Shared Operator -(ByVal aA As Angle, ByVal aB As Angle) As Angle
Return New Angle(Angle:=aA.Angle - aB.Angle)
End Operator
Public Overrides Function ToString() As String
Return String.Format("{0}°", mAngle)
End Function
End Class
So now it much easier to write the equation.
Dim T = (A-B) + C





MultiQuote


|