Chapter 16. Overloading C++ Operators
C++ allows you to redefine the meanings of operators, such as
+, -, and
=, for your classes. Many object-oriented languages do not provide this capability, so you might be tempted to disregard its usefulness in C++. However, it can be beneficial for making your classes behave similarly to built-in types such as
doubles. It is even possible to write classes that look like arrays, functions, or pointers!
Chapters 3 and 5 introduced object-oriented design and operator overloading, respectively. Chapters 8 and 9 presented the syntax details for objects and for basic operator overloading. This chapter picks up operator overloading where Chapter 9 left off. The STL, introduced in Chapter 4, and described in detail in Chapters 21 to 23, uses operator overloading extensively. You should read and understand this chapter before tackling Chapters 21 to 23.
This chapter focuses on the syntax and basic semantics of operator overloading. Practical examples are provided for most of the operators, but for a few of them, practical examples are postponed until later chapters.
This chapter does not repeat information contained in Chapter 9.
The contents of this chapter include:
An overview of operator overloading
Rationale for overloading operators
Limitations, caveats, and choices in operator overloading
Summary of operators you can, cannot, and should not overload
How to overload unary plus, unary minus, increment, and decrement
How to overload the I/O streams ...