In many enhanced features of Visual Basic 2005, the operator's overload is one of the most powerful. The operator overload allows an operator to be defined on any data type, or even the base type created by yourself. The most classic operator is an example of the definition of the plurality of complexes. A simplified Complex class with the " " heavy-duty operator may be the following form: Public Class Complex
Public Real As Double Public IMAG As Double
Public Sub New (Byval Imagpart As Double) Real = realpart imag = iMagPart End Sub
Shared Operator (Byval RHS As Complex) AS Complex Return New Complex (LHS.REAL RHS.REAL, LHS.IMAG RHS.IMAG) End Operator
End Class now, we can use the " " operator to make two plurals with a very intuitive way: DIM LHS As Complex = New Complex (2.0, 2.5) DIM RHS As Complex = New Complex (3.0, 3.5 DIM RES AS Complex = LHS RHS 'Res.Real = 5.0, res.imag = 6.0 You can also overload the conversion operator for your custom type. If you try to convert the value of the above RES, you will get a compilation error tells you that the Complex class cannot be converted to String. If you consider using Res. Tostring, you will find that the TOSTRING method of the complex value is just its default type name. You can solve these problems by overloading the CType conversion operator and the toString method, just like this: public shared narrowing operator ctype (byval value as complex) AS String 'There is no special requirement here, so Narrowing keywords can also be Change to widening keyword, 淌 淌 Return Value.Real.Tostring & "I" & value.imag.tostringend Operator
'淌 注: Author's original code is incorrect, unable to enable the TOString method of the basic class Object type! Public overrides function daytring (byval value as complex) AS String Return Value.Real.Tostring & "I" & value.imag.tostringend Function
'淌 淌: The correct code is as follows! Public overrides function torsion () AS STRING RETURN Real.toTnow & "I" & imag.tostringend Function Now ctype (res, string) and res. TOTRING return value is the same as we want: "5.0i6.0" (The actually obtained "5i6", Visual Basic slightly, 注 省). The conversion operator must be modified by Narrowing, or be modified by widening to explain the nature of the conversion. @ The following is the text for your reference @Operator Overloading and Conversion OperatorsOne of the most powerful additions to Visual Basic 2005 is operator overloading. Operator overloading lets you define operators that act on any type you want, even to the point of creating your own base types . The classic operator-overloading example is adding complex numbers A simplified Complex class with the operator overloaded might look like this:. Public class ComplexPublic Real As Double Public Imag As Double
Public Sub New (Byval Imagpart As Double) Real = realpart imag = iMagPart End Sub
Shared Operator (Byval RHS As Complex) AS Complex Return New Complex (LHS.REAL RHS.REAL, LHS.IMAG RHS.IMAG) End Operator