Prev | Current Page 200 | Next

Guy Fouch?©, Trey Nash

"Accelerated VB 2008"

Structures and classes that are immutable, such as System.String, are perfect candidates
for implementing custom operators. This behavior is natural for operators such as
Boolean, which usually return a type different than the types passed into the operator.
CHAPTER 7 n OPERATOR OVERLOADING 119
Does Parameter Order Matter?
Let??™s create a structure to represent complex numbers. The first version looks like this:
Public Structure Complex
Private Real As Double
Private Imaginary As Double
Public Sub New(ByVal real As Double, ByVal imaginary As Double)
Me.Real = real
Me.Imaginary = imaginary
End Sub
Public Shared Function Add(ByVal lhs As Complex, ByVal rhs As Complex) _
As Complex
Return New Complex(lhs.Real + rhs.Real, lhs.Imaginary + rhs.Imaginary)
End Function
Public Shared Operator +(ByVal lhs As Complex, ByVal rhs As Complex) As Complex
Return Add(lhs, rhs)
End Operator
End Structure
Suppose you need to add instances of Complex together, but would like to be able to add a
plain-old Double variable to the Complex instance. Adding this functionality is no problem,
since you can overload the Operator + method such that one parameter is a Complex and the
other is a Double. That declaration could look like the following:
Public Shared Operator +(ByVal lhs As Complex, ByVal rhs As Double) As Complex
With this operator declared and defined on the Complex structure, you can now write code
such as the following:
Dim cpx1 As New Complex(1.


Pages:
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
śmieszne dowcipy dieta light Connie Talbot zarządzanie nieruchomościami życzenia