- Single-argument constructor: allow conversion from a particular type to initialize an object.
- Assignment operator: allow conversion from a particular type on assignment.
- Type-cast operator: allow conversion to a particular type.
- For a construction with implicit initialization ('Dim As DT u = v'), the compiler uses the matched constructor (for DT type / v type).
- For an implicit assignment ('u = v'), the compiler uses the matched let operator (for DT type / v type).
- For an implicit addition ('u = u0 + v' or 'u += v'), the compiler uses firstly the matched cast operator (for DT type / v type), then the matched let operator (for DT type / v type).
Code: Select all
Type DT '' Dynamic Type
Public:
Declare Constructor ()
Declare Constructor (Byval rhs As Integer)
Declare Constructor (Byval rhs As Single)
Declare Constructor (Byref rhs As String)
Declare Operator Let (Byval rhs As Integer)
Declare Operator Let (Byval rhs As Single)
Declare Operator Let (Byref rhs As String)
Declare Operator Cast () As Integer
Declare Operator Cast () As Single
Declare Operator Cast () As String
Declare Property myType () As String
Private:
Dim As String _type
Union
Dim As Integer _integer
Dim As Single _single
End Union
Dim As String _string '' Var-len strings cannot be part of UNION
End Type
Constructor DT ()
End Constructor
Constructor DT (Byval rhs As Integer)
This._type = "INTEGER"
This._integer = rhs
End Constructor
Constructor DT (Byval rhs As Single)
This._type = "SINGLE"
This._single = rhs
End Constructor
Constructor DT (Byref rhs As String)
This._type = "STRING"
This._string = rhs
End Constructor
Operator DT.Let (Byval rhs As Integer)
This._type = "INTEGER"
This._string = ""
This._integer = rhs
End Operator
Operator DT.Let (Byval rhs As Single)
This._type = "SINGLE"
This._string = ""
This._single = rhs
End Operator
Operator DT.Let (Byref rhs As String)
This._type = "STRING"
This._string = rhs
End Operator
Operator DT.Cast () As Integer
Return This._integer
End Operator
Operator DT.Cast () As Single
Return This._single
End Operator
Operator DT.Cast () As String
If This._type = "INTEGER" Then Return Str(This._integer)
If This._type = "SINGLE" Then Return Str(This._single)
If This._type = "STRING" Then Return This._string
End Operator
Property DT.myType () As String
Return This._type
End Property
Dim As DT u
u = 100 ''
u = u + 20
u += 3
Print u.myType, u
Dim As Integer vinteger = u
Print vinteger
Print
u = 456.7
u = u + 0.08
u += 0.009
Print u.myType, u
Dim As Single vsingle = u
Print vsingle
Print
u = "a user "
u = u + "Dynamic "
u += "Type"
Print u.myType, u
Dim As String vstring = u
Print vstring
Print
Sleep