Chapter 28. Overloading Operators
In Lesson 27 you learned how to overload a class's methods. Visual Basic also lets you overload operators such as + and * to give them new meanings when working with the structures and classes that you create. For example, you could overload the + operator so the program would know how to add a Student
object and a Course
object. Sometimes that enables you to use a more natural syntax when you're working with objects.
In this lesson, you learn how to overload operators so you can use them to manipulate objects.
Warning
Before you jump into operator overloading, be warned that just because you can overload an operator doesn't mean you should. You should only overload operators in intuitive ways.
For example, it makes sense to overload the +
operator so you can add two ComplexNumber
objects. It might also make sense to overload +
so you can add an item to a purchase order.
It probably doesn't make sense to define +
between two Employee
objects to return a list of projects that include both employees. You could do that but you probably shouldn't because it would be confusing.
OVERLOADABLE OPERATORS
In Visual Basic, you can overload unary, binary, and logical operators. Table 28-1 summarizes the operators that you can overload.
Table 28.1. TABLE 28-1
TYPE | OPERATORS |
---|---|
Unary |
|
Binary |
|
Comparison |
|
The comparison operators come in pairs. For example, if you overload the ...
Get Stephens' Visual Basic® Programming 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.