Operator Overload Demo
Imports System
Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim X, Y As Complex
X = New Complex(1, 2)
Y = New Complex(3, 4)
Console.WriteLine( (X + Y).ToString )
Console.WriteLine( (X - Y).ToString )
Console.WriteLine( (X * Y).ToString )
Console.WriteLine( (X = Y).ToString )
Console.WriteLine( (X <> Y).ToString )
Console.WriteLine( (-X).ToString )
Dim abs_x As Double = CDbl(X)
Console.WriteLine( abs_x.ToString )
End Sub
End Class
Public Class Complex
Public realPart As Double
Public imaginaryPart As Double
' Constructors.
Public Sub New()
End Sub
Public Sub New(ByVal real_part As Double, ByVal imaginary_part As Double)
realPart = real_part
imaginaryPart = imaginary_part
End Sub
' ToString.
Public Overrides Function ToString() As String
Return realPart.ToString & " + " & imaginaryPart.ToString & "i"
End Function
' Operators.
Public Shared Operator *(ByVal c1 As Complex, ByVal c2 As Complex) As Complex
Return New Complex( _
c1.realPart * c2.realPart - c1.imaginaryPart * c2.imaginaryPart, _
c1.realPart * c2.imaginaryPart + c1.imaginaryPart * c2.realPart)
End Operator
Public Shared Operator +(ByVal c1 As Complex, ByVal c2 As Complex) As Complex
Return New Complex( _
c1.realPart + c2.realPart, _
c1.imaginaryPart + c2.imaginaryPart)
End Operator
Public Shared Operator -(ByVal c1 As Complex, ByVal c2 As Complex) As Complex
Return New Complex( _
c1.realPart - c2.realPart, _
c1.imaginaryPart - c2.imaginaryPart)
End Operator
Public Shared Operator =(ByVal c1 As Complex, ByVal c2 As Complex) As Boolean
Return (c1.realPart = c2.realPart) AndAlso (c1.imaginaryPart = c2.imaginaryPart)
End Operator
Public Shared Operator <>(ByVal c1 As Complex, ByVal c2 As Complex) As Boolean
Return (c1.realPart <> c2.realPart) OrElse (c1.imaginaryPart <> c2.imaginaryPart)
End Operator
Public Shared Operator -(ByVal c1 As Complex) As Complex
Return New Complex(c1.imaginaryPart, c1.realPart)
End Operator
Public Shared Narrowing Operator CType(ByVal c1 As Complex) As Double
Return System.Math.Sqrt(c1.realPart * c1.realPart + c1.imaginaryPart * c1.imaginaryPart)
End Operator
End Class
Related examples in the same category