![]() |
|||||||||
8.1 Introduction to Operator Overloading |
|||||||||
|
Operator overloading is the ability to define a new meaning for an existing (built-in) operator. The list of operators includes mathematical operators (+, -, *, etc), relational operators ( <, >, ==, etc), logical operators (&&, ||, !, etc.), access operators ([], ->), the assignment operator (=), stream I/O operators ( <<, >>), type conversion operators, and several others. While all of these operators have predefined and unchangeable meanings for the built-in types, each operator can be given a specific interpretation for individual user-defined classes or combinations of user-defined classes. C++ is particularly generous in the flexibility it offers to programmers in extending these built-in operators; not all object-oriented languages allow this. There are a number of reasons why a class designer may decide to provide extensions to one or more of the built-in operators: natural, suggestive usage: The most natural way to convey the intended meaning of an operation
may be through the predefined operators. For example, in defining
a class to represent complex or rational numbers, the best way
to represent adding two complex numbers or adding two rational
numbers is by giving a new (extended) meaning to the plus operator
(+) rather than invent a member function with a suggestive name
("addTo"). semantic integrity: In order to copy the objects beingpointed to, classes that have
pointers to objects frequentlyneed a specialized assignment operator.
The failure to properly handle assignments can lead to either
memory leaks or run-time errors. uniformity with base types: Templates often impose requirements on their arguments that can
only be met by both built-in types and user-defined types when
the user-defined types provide overloaded operations. For example,
a Set template may require that its instantiating type have an
equality operator (==) in order to implement the test for membership
in the Set. In many cases, the use of overloaded operators serves some or all of these purposes simultaneously.
|
|||||||||
|
|||||||||