- •Contents
- •Introduction
- •Who This Book Is For
- •What This Book Covers
- •How This Book Is Structured
- •What You Need to Use This Book
- •Conventions
- •Source Code
- •Errata
- •p2p.wrox.com
- •The Basics of C++
- •The Obligatory Hello, World
- •Namespaces
- •Variables
- •Operators
- •Types
- •Conditionals
- •Loops
- •Arrays
- •Functions
- •Those Are the Basics
- •Diving Deeper into C++
- •Pointers and Dynamic Memory
- •Strings in C++
- •References
- •Exceptions
- •The Many Uses of const
- •C++ as an Object-Oriented Language
- •Declaring a Class
- •Your First Useful C++ Program
- •An Employee Records System
- •The Employee Class
- •The Database Class
- •The User Interface
- •Evaluating the Program
- •What Is Programming Design?
- •The Importance of Programming Design
- •Two Rules for C++ Design
- •Abstraction
- •Reuse
- •Designing a Chess Program
- •Requirements
- •Design Steps
- •An Object-Oriented View of the World
- •Am I Thinking Procedurally?
- •The Object-Oriented Philosophy
- •Living in a World of Objects
- •Object Relationships
- •Abstraction
- •Reusing Code
- •A Note on Terminology
- •Deciding Whether or Not to Reuse Code
- •Strategies for Reusing Code
- •Bundling Third-Party Applications
- •Open-Source Libraries
- •The C++ Standard Library
- •Designing with Patterns and Techniques
- •Design Techniques
- •Design Patterns
- •The Reuse Philosophy
- •How to Design Reusable Code
- •Use Abstraction
- •Structure Your Code for Optimal Reuse
- •Design Usable Interfaces
- •Reconciling Generality and Ease of Use
- •The Need for Process
- •Software Life-Cycle Models
- •The Stagewise and Waterfall Models
- •The Spiral Method
- •The Rational Unified Process
- •Software-Engineering Methodologies
- •Extreme Programming (XP)
- •Software Triage
- •Be Open to New Ideas
- •Bring New Ideas to the Table
- •Thinking Ahead
- •Keeping It Clear
- •Elements of Good Style
- •Documenting Your Code
- •Reasons to Write Comments
- •Commenting Styles
- •Comments in This Book
- •Decomposition
- •Decomposition through Refactoring
- •Decomposition by Design
- •Decomposition in This Book
- •Naming
- •Choosing a Good Name
- •Naming Conventions
- •Using Language Features with Style
- •Use Constants
- •Take Advantage of const Variables
- •Use References Instead of Pointers
- •Use Custom Exceptions
- •Formatting
- •The Curly Brace Alignment Debate
- •Coming to Blows over Spaces and Parentheses
- •Spaces and Tabs
- •Stylistic Challenges
- •Introducing the Spreadsheet Example
- •Writing Classes
- •Class Definitions
- •Defining Methods
- •Using Objects
- •Object Life Cycles
- •Object Creation
- •Object Destruction
- •Assigning to Objects
- •Distinguishing Copying from Assignment
- •The Spreadsheet Class
- •Freeing Memory with Destructors
- •Handling Copying and Assignment
- •Different Kinds of Data Members
- •Static Data Members
- •Const Data Members
- •Reference Data Members
- •Const Reference Data Members
- •More about Methods
- •Static Methods
- •Const Methods
- •Method Overloading
- •Default Parameters
- •Inline Methods
- •Nested Classes
- •Friends
- •Operator Overloading
- •Implementing Addition
- •Overloading Arithmetic Operators
- •Overloading Comparison Operators
- •Building Types with Operator Overloading
- •Pointers to Methods and Members
- •Building Abstract Classes
- •Using Interface and Implementation Classes
- •Building Classes with Inheritance
- •Extending Classes
- •Overriding Methods
- •Inheritance for Reuse
- •The WeatherPrediction Class
- •Adding Functionality in a Subclass
- •Replacing Functionality in a Subclass
- •Respect Your Parents
- •Parent Constructors
- •Parent Destructors
- •Referring to Parent Data
- •Casting Up and Down
- •Inheritance for Polymorphism
- •Return of the Spreadsheet
- •Designing the Polymorphic Spreadsheet Cell
- •The Spreadsheet Cell Base Class
- •The Individual Subclasses
- •Leveraging Polymorphism
- •Future Considerations
- •Multiple Inheritance
- •Inheriting from Multiple Classes
- •Naming Collisions and Ambiguous Base Classes
- •Interesting and Obscure Inheritance Issues
- •Special Cases in Overriding Methods
- •Copy Constructors and the Equals Operator
- •The Truth about Virtual
- •Runtime Type Facilities
- •Non-Public Inheritance
- •Virtual Base Classes
- •Class Templates
- •Writing a Class Template
- •How the Compiler Processes Templates
- •Distributing Template Code between Files
- •Template Parameters
- •Method Templates
- •Template Class Specialization
- •Subclassing Template Classes
- •Inheritance versus Specialization
- •Function Templates
- •Function Template Specialization
- •Function Template Overloading
- •Friend Function Templates of Class Templates
- •Advanced Templates
- •More about Template Parameters
- •Template Class Partial Specialization
- •Emulating Function Partial Specialization with Overloading
- •Template Recursion
- •References
- •Reference Variables
- •Reference Data Members
- •Reference Parameters
- •Reference Return Values
- •Deciding between References and Pointers
- •Keyword Confusion
- •The const Keyword
- •The static Keyword
- •Order of Initialization of Nonlocal Variables
- •Types and Casts
- •typedefs
- •Casts
- •Scope Resolution
- •Header Files
- •C Utilities
- •Variable-Length Argument Lists
- •Preprocessor Macros
- •How to Picture Memory
- •Allocation and Deallocation
- •Arrays
- •Working with Pointers
- •Array-Pointer Duality
- •Arrays Are Pointers!
- •Not All Pointers Are Arrays!
- •Dynamic Strings
- •C-Style Strings
- •String Literals
- •The C++ string Class
- •Pointer Arithmetic
- •Custom Memory Management
- •Garbage Collection
- •Object Pools
- •Function Pointers
- •Underallocating Strings
- •Memory Leaks
- •Double-Deleting and Invalid Pointers
- •Accessing Out-of-Bounds Memory
- •Using Streams
- •What Is a Stream, Anyway?
- •Stream Sources and Destinations
- •Output with Streams
- •Input with Streams
- •Input and Output with Objects
- •String Streams
- •File Streams
- •Jumping around with seek() and tell()
- •Linking Streams Together
- •Bidirectional I/O
- •Internationalization
- •Wide Characters
- •Non-Western Character Sets
- •Locales and Facets
- •Errors and Exceptions
- •What Are Exceptions, Anyway?
- •Why Exceptions in C++ Are a Good Thing
- •Why Exceptions in C++ Are a Bad Thing
- •Our Recommendation
- •Exception Mechanics
- •Throwing and Catching Exceptions
- •Exception Types
- •Throwing and Catching Multiple Exceptions
- •Uncaught Exceptions
- •Throw Lists
- •Exceptions and Polymorphism
- •The Standard Exception Hierarchy
- •Catching Exceptions in a Class Hierarchy
- •Writing Your Own Exception Classes
- •Stack Unwinding and Cleanup
- •Catch, Cleanup, and Rethrow
- •Use Smart Pointers
- •Common Error-Handling Issues
- •Memory Allocation Errors
- •Errors in Constructors
- •Errors in Destructors
- •Putting It All Together
- •Why Overload Operators?
- •Limitations to Operator Overloading
- •Choices in Operator Overloading
- •Summary of Overloadable Operators
- •Overloading the Arithmetic Operators
- •Overloading Unary Minus and Unary Plus
- •Overloading Increment and Decrement
- •Overloading the Subscripting Operator
- •Providing Read-Only Access with operator[]
- •Non-Integral Array Indices
- •Overloading the Function Call Operator
- •Overloading the Dereferencing Operators
- •Implementing operator*
- •Implementing operator->
- •What in the World Is operator->* ?
- •Writing Conversion Operators
- •Ambiguity Problems with Conversion Operators
- •Conversions for Boolean Expressions
- •How new and delete Really Work
- •Overloading operator new and operator delete
- •Overloading operator new and operator delete with Extra Parameters
- •Two Approaches to Efficiency
- •Two Kinds of Programs
- •Is C++ an Inefficient Language?
- •Language-Level Efficiency
- •Handle Objects Efficiently
- •Use Inline Methods and Functions
- •Design-Level Efficiency
- •Cache as Much as Possible
- •Use Object Pools
- •Use Thread Pools
- •Profiling
- •Profiling Example with gprof
- •Cross-Platform Development
- •Architecture Issues
- •Implementation Issues
- •Platform-Specific Features
- •Cross-Language Development
- •Mixing C and C++
- •Shifting Paradigms
- •Linking with C Code
- •Mixing Java and C++ with JNI
- •Mixing C++ with Perl and Shell Scripts
- •Mixing C++ with Assembly Code
- •Quality Control
- •Whose Responsibility Is Testing?
- •The Life Cycle of a Bug
- •Bug-Tracking Tools
- •Unit Testing
- •Approaches to Unit Testing
- •The Unit Testing Process
- •Unit Testing in Action
- •Higher-Level Testing
- •Integration Tests
- •System Tests
- •Regression Tests
- •Tips for Successful Testing
- •The Fundamental Law of Debugging
- •Bug Taxonomies
- •Avoiding Bugs
- •Planning for Bugs
- •Error Logging
- •Debug Traces
- •Asserts
- •Debugging Techniques
- •Reproducing Bugs
- •Debugging Reproducible Bugs
- •Debugging Nonreproducible Bugs
- •Debugging Memory Problems
- •Debugging Multithreaded Programs
- •Debugging Example: Article Citations
- •Lessons from the ArticleCitations Example
- •Requirements on Elements
- •Exceptions and Error Checking
- •Iterators
- •Sequential Containers
- •Vector
- •The vector<bool> Specialization
- •deque
- •list
- •Container Adapters
- •queue
- •priority_queue
- •stack
- •Associative Containers
- •The pair Utility Class
- •multimap
- •multiset
- •Other Containers
- •Arrays as STL Containers
- •Strings as STL Containers
- •Streams as STL Containers
- •bitset
- •The find() and find_if() Algorithms
- •The accumulate() Algorithms
- •Function Objects
- •Arithmetic Function Objects
- •Comparison Function Objects
- •Logical Function Objects
- •Function Object Adapters
- •Writing Your Own Function Objects
- •Algorithm Details
- •Utility Algorithms
- •Nonmodifying Algorithms
- •Modifying Algorithms
- •Sorting Algorithms
- •Set Algorithms
- •The Voter Registration Audit Problem Statement
- •The auditVoterRolls() Function
- •The getDuplicates() Function
- •The RemoveNames Functor
- •The NameInList Functor
- •Testing the auditVoterRolls() Function
- •Allocators
- •Iterator Adapters
- •Reverse Iterators
- •Stream Iterators
- •Insert Iterators
- •Extending the STL
- •Why Extend the STL?
- •Writing an STL Algorithm
- •Writing an STL Container
- •The Appeal of Distributed Computing
- •Distribution for Scalability
- •Distribution for Reliability
- •Distribution for Centrality
- •Distributed Content
- •Distributed versus Networked
- •Distributed Objects
- •Serialization and Marshalling
- •Remote Procedure Calls
- •CORBA
- •Interface Definition Language
- •Implementing the Class
- •Using the Objects
- •A Crash Course in XML
- •XML as a Distributed Object Technology
- •Generating and Parsing XML in C++
- •XML Validation
- •Building a Distributed Object with XML
- •SOAP (Simple Object Access Protocol)
- •. . . Write a Class
- •. . . Subclass an Existing Class
- •. . . Throw and Catch Exceptions
- •. . . Read from a File
- •. . . Write to a File
- •. . . Write a Template Class
- •There Must Be a Better Way
- •Smart Pointers with Reference Counting
- •Double Dispatch
- •Mix-In Classes
- •Object-Oriented Frameworks
- •Working with Frameworks
- •The Model-View-Controller Paradigm
- •The Singleton Pattern
- •Example: A Logging Mechanism
- •Implementation of a Singleton
- •Using a Singleton
- •Example: A Car Factory Simulation
- •Implementation of a Factory
- •Using a Factory
- •Other Uses of Factories
- •The Proxy Pattern
- •Example: Hiding Network Connectivity Issues
- •Implementation of a Proxy
- •Using a Proxy
- •The Adapter Pattern
- •Example: Adapting an XML Library
- •Implementation of an Adapter
- •Using an Adapter
- •The Decorator Pattern
- •Example: Defining Styles in Web Pages
- •Implementation of a Decorator
- •Using a Decorator
- •The Chain of Responsibility Pattern
- •Example: Event Handling
- •Implementation of a Chain of Responsibility
- •Using a Chain of Responsibility
- •Example: Event Handling
- •Implementation of an Observer
- •Using an Observer
- •Chapter 1: A Crash Course in C++
- •Chapter 3: Designing with Objects
- •Chapter 4: Designing with Libraries and Patterns
- •Chapter 5: Designing for Reuse
- •Chapter 7: Coding with Style
- •Chapters 8 and 9: Classes and Objects
- •Chapter 11: Writing Generic Code with Templates
- •Chapter 14: Demystifying C++ I/O
- •Chapter 15: Handling Errors
- •Chapter 16: Overloading C++ Operators
- •Chapter 17: Writing Efficient C++
- •Chapter 19: Becoming Adept at Testing
- •Chapter 20: Conquering Debugging
- •Chapter 24: Exploring Distributed Objects
- •Chapter 26: Applying Design Patterns
- •Beginning C++
- •General C++
- •I/O Streams
- •The C++ Standard Library
- •C++ Templates
- •Integrating C++ and Other Languages
- •Algorithms and Data Structures
- •Open-Source Software
- •Software-Engineering Methodology
- •Programming Style
- •Computer Architecture
- •Efficiency
- •Testing
- •Debugging
- •Distributed Objects
- •CORBA
- •XML and SOAP
- •Design Patterns
- •Index
Chapter 16
How to overload the function call operator
How to overload the dereferencing operators (* and ->)
How to write conversion operators
How to overload the memory allocation and deallocation operators
Over view of Operator Overloading
As Chapter 1 reviewed, operators in C++ are symbols such as +, <, *, and <<. They work on built-in types such as int and double to allow you to perform arithmetic, logical, and other operations. There are also operators such as -> and & that allow you to dereference pointers. The concept of operators in C++ is broad, and even includes [] (array index), () (function call), and the memory allocation and deallocation routines.
Operator overloading allows you to change the behavior of language operators for your classes. However, this capability comes with rules, limitations, and choices.
Why Overload Operators?
Before learning how to overload operators, you probably want to know why you would ever want to do so. The reasons vary for the different operators, but the general guiding principle is to make your classes behave like built-in types. The closer your classes are to built-in types, the easier they will be for clients to use. For example, if you want to write a class to represent fractions, it’s quite helpful to have the ability to define what +, -, *, and / mean when applied to objects of that class.
The second reason to overload operators is to gain greater control over behavior in your program. For example, you can overload memory allocation and deallocation routines for your classes to specify exactly how memory should be distributed and reclaimed for each new object.
It’s important to emphasize that operator overloading doesn’t necessarily make things easier for you as the class developer; its main purpose is to make things easier for clients of the class.
Limitations to Operator Overloading
Here is a list of things you cannot do when you overload operators:
You cannot add new operator symbols. You can only redefine the meanings of operators already in the language. The table in the “Summary of Overloadable Operators” section lists all of the operators that you can overload.
There are a few operators that you cannot overload, such as . (member access in an object), :: (scope resolution operator), sizeof, ?: (the ternary operator), and a few others. The table lists all the operators that you can overload. The operators that you can’t overload are usually not those you would care to overload anyway, so we don’t think you’ll find this restriction limiting.
You cannot change the arity of the operator. The arity describes the number of arguments, or operands, associated with the operator. Unary operators, such as ++, work on only one operand. Binary operators, such as +, work on two operands. There is only one ternary operator: ?:. The
432
Overloading C++ Operators
main place where this limitation might bother you is when overloading [] (array brackets), as discussed below.
You cannot change the precedence or associativity of the operator. These rules determine in which order operators are evaluated in a statement. Again, this constraint shouldn’t be cause for concern in most programs because there are rarely benefits to changing the order of evaluation.
You cannot redefine operators for built-in types. The operator must be a method in a class, or at least one of the arguments to a global overloaded operator function must be a user-defined type (e.g., a class). This means that you can’t do something ridiculous such as redefine + for ints to mean subtraction (though you could do so for your classes). The one exception to this rule is the memory allocation and deallocation routines; you can replace the global routines for all memory allocation in your program.
Some of the operators already mean two different things. For example, the – operator can be used as a binary operator, as in x = y - z or as a unary operator, as in x = -y;. The * operator can be used for multiplication or for dereferencing a pointer. The << operator is the insertion operator or the left-shift operator, depending on context. You can overload both meanings of operators with dual meanings.
Choices in Operator Overloading
When you overload an operator, you write a function or method with the name operatorX, where X is the symbol for some operator. For example, in Chapter 9, you saw operator+ declared for SpreadsheetCell objects like this:
friend const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
There are several choices involved in each overloaded operator function or method you write.
Method or Global Function
First, you must decide whether your operator should be a method of your class or a global function (usually a friend of the class). How do you choose? First, you need to understand the difference between these two choices. When the operator is a method of a class, the left-hand-side of the operator expression must always be an object of that class. If you write a global function, the left-hand-side can be an object of a different type.
There are three different types of operators:
Operators that must be methods. The C++ language requires some operators to be methods of a class because they don’t make sense outside of a class. For example, operator= is tied so closely to the class that it can’t exist anywhere else. The table in the “Summary of Overloadable Operators” section lists those operators that must be methods. For these, the choice of method or global function is simple! However, most operators do not impose this requirement.
Operators that must be global functions. Whenever you need to allow the left-hand side of the operator to be a variable of a different type from your class, you must make the operator a global function. This rule applies specifically to operator<< and operator>>, where the left-hand side is the iostream object, not an object of your class. Additionally, commutative operators like binary + and – should allow variables that are not objects of your class on the left-hand side. This problem was explained previously in Chapter 9.
433
Chapter 16
Operators that can be either methods or global functions. There is some disagreement in the C++ community on whether it’s better to write methods or global functions to overload operators. However, we recommend the following rule: make every operator a method unless you must make it a global function as described previously. One major advantage to this rule is that methods can be virtual, but friend functions cannot. Therefore, when you plan to write overloaded operators in an inheritance tree, you should make them methods if possible.
When you write an overloaded operator as a method, you should mark the entire method const if it doesn’t change the object. That way, it can be called on const objects.
Choosing Argument Types
You are somewhat limited in your choice of argument types because you can’t usually change the number of arguments (although there are exceptions, which are explained later in this chapter). For example, operator+ must always have two arguments if it is a global function; one argument if it’s a method.
The compiler issues an error if it differs from this standard. In this sense, the operator functions are different from normal functions, which you can overload with any number of parameters. Additionally, although you can write the operator for whichever types you want, the choice is usually constrained by the class for which you are writing the operator. For example, if you want to implement addition for class T, you wouldn’t write an operator+ that takes two strings! The real choice arises when you try to determine whether to take parameters by value or by reference, and whether or not to make them const.
The choice of value vs. reference is easy: you should take every parameter by reference. As explained in Chapters 9 and 12, never pass objects by value if you can pass-by-reference instead!
The const decision is also trivial: mark every parameter const unless you actually modify it. The table in the “Summary of Overloadable Operators” section shows sample prototypes for each operator, with the arguments marked const and reference as appropriate.
Choosing Return Types
Recall that C++ doesn’t determine overload resolution based on return type. Thus, you can specify any return type you want when you write overloaded operators. However, just because you can do something doesn’t mean you should do it. This flexibility implies that you could write confusing code in which comparison operators return pointers, and arithmetic operators return bools! However, you shouldn’t do that. Instead, you should write your overloaded operators such that they return the same types as the operators do for the built-in types. If you write a comparison operator, return a bool. If you write an arithmetic operator, return an object representing the result of the arithmetic. Sometimes the return type is not obvious at first. For example, as you learned in Chapter 8, operator= should return a reference to the object on which it’s called in order to support nested assignment. Other operators have similarly tricky return types, all of which are summarized in the table in the “Summary of Overloadable Operators” section.
The same choices of reference and const apply to return types as well. However, for return values, the choices are more difficult. The general rule for value or reference is to return a reference if you can; otherwise, return a value. How do you know when you can return a reference? This choice applies only to operators that return objects: the choice is moot for the comparison operators that return bool, the conversion operators that have no return type, and the function call operator, which may return any type you want. If your operator constructs a new object, then you must return that new object by value. If it
434
Overloading C++ Operators
does not construct a new object, you can return a reference to the object on which the operator is called, or one of its arguments. The table in the “Summary of Overloadable Operators” section shows examples.
A return value that can be modified as an lvalue (the left-hand-side of an assignment expression) must be non-const. Otherwise, it should be const. More operators than you might think at first return lvalues, including all of the assignment operators (operator=, operator+=, operator-=, etc.).
If you are in doubt about the appropriate return type, simply consult the table in the “Summary of Overloadable Operators” section.
Choosing Behavior
You can provide whichever implementation you want in an overloaded operator. For example, you could write an operator+ that launches a game of Scrabble. However, as described in Chapter 5, you should generally constrain your implementations to provide behaviors that clients expect. Write operator+ so that it performs addition, or something like addition, such as string concatenation.
This chapter explains how you should implement your overloaded operators. In exceptional circumstances, you might want to differ from these recommendations, but, in general, you should follow the standard patterns.
Operators You Shouldn’t Overload
There are a few operators that it is rarely a good idea to overload, even though it is permitted. Specifically, the address-of operator (operator&) is not particularly useful to overload, and leads to confusion if you do because you are changing fundamental language behavior (taking addresses of variables) in potentially unexpected ways.
Additionally, you should avoid overloading the binary Boolean operators operator&& and operator|| because you lose C++’s short-circuit evaluation rules.
Finally, you should not overload the comma operator (operator,). Yes, you read that correctly: there really is a comma operator in C++. It’s also called the sequencing operator, and is used to separate two expressions in a single statement, while guaranteeing that they are evaluated left to right. There is rarely (if ever) a good reason to overload this operator.
Summary of Overloadable Operators
The following table lists all of the operators that you can overload, specifies whether they should be methods of the class or global friend functions, summarizes when you should (or should not) overload them, and provides sample prototypes, showing the proper return values.
This table should be a useful reference in the future when you want to sit down and write an overloaded operator. You’re bound to forget which return type you should use, and whether or not the function should be a method. We’re looking forward to referring to this table ourselves!
In this table, T is the name of the class for which the overloaded operator is written, and E is a different type (not the name of the class).
435
Chapter 16
|
|
Method or |
|
|
|
Name or |
Global Friend |
When to |
|
Operator |
Category |
Function |
Overload |
Sample Prototype |
|
|
|
|
|
operator+ |
Binary |
Global friend |
Whenever you |
friend const T |
operator- |
arithmetic |
function |
want to |
operator+(const |
operator* |
|
recommended |
provide these |
T&, const T&); |
operator/ |
|
|
operations for |
|
operator% |
|
|
your class |
|
operator- |
Unary |
Method |
Whenever you |
const T operator-() |
operator+ |
arithmetic |
recommended |
want to |
const; |
operator~ |
and bitwise |
|
provide these |
|
|
operators |
|
operations for |
|
|
|
|
your class |
|
operator++ |
Increment |
Method |
Whenever you |
T& operator++(); |
operator-- |
and |
recommended |
overload |
|
|
decrement |
|
binary + and - |
const T |
|
|
|
|
operator++(int); |
operator= |
Assignment |
Method |
Whenever |
T& operator=(const |
|
operator |
required |
you have |
T&); |
|
|
|
dynamically |
|
|
|
|
allocated |
|
|
|
|
memory in the |
|
|
|
|
object or want |
|
|
|
|
to prevent |
|
|
|
|
assignment, as |
|
|
|
|
described in |
|
|
|
|
Chapter 9 |
|
operator+= |
Shorthand |
Method |
Whenever you |
T& operator+=(const |
operator-= |
arithmetic |
recommended |
overload the |
T&); |
operator*/ |
operator |
|
binary |
|
operator/= |
assignments |
|
arithmetic |
|
operator%= |
|
|
operators |
|
operator<< |
Binary bitwise |
Global friend |
Whenever you |
friend const T |
operator>> |
operators |
function |
want to |
operator<<(const |
operator& |
|
recommended |
provide these |
T&, const T&); |
operator| |
|
|
operations |
|
operator^ |
|
|
|
|
operator<<= |
Shorthand |
Method |
Whenever you |
T& operator<<= |
operator>>= |
bitwise |
recommended |
overload the |
(const T&); |
operator&= |
operator |
|
binary bitwise |
|
operator|= |
assignments |
|
operators |
|
operator^= |
|
|
|
|
|
|
|
|
|
436
Overloading C++ Operators
|
|
Method or |
|
|
|
Name or |
Global Friend |
When to |
|
Operator |
Category |
Function |
Overload |
Sample Prototype |
|
|
|
|
|
operator< |
Binary |
Global friend |
Whenever you |
friend bool |
operator> |
comparison |
function |
want to |
operator<(const T&, |
operator<= |
operators |
recommended |
provide these |
const T&); |
operator>= |
|
|
operations |
|
operator== |
|
|
|
|
operator<< |
I/O stream |
Global friend |
Whenever you |
friend ostream |
operator>> |
operators |
function |
want to |
&operator<< |
|
(insertion and |
recommended |
provide these |
(ostream&, |
|
extraction) |
|
operations |
const T&); |
|
|
|
|
friend istream |
|
|
|
|
&operator>> |
|
|
|
|
(istream&, T&); |
operator! |
Boolean |
Member |
Rarely; use |
bool operator!() |
|
negation |
function |
bool or void* |
const; |
|
operator |
recommended |
conversion |
|
|
|
|
instead |
|
operator&& |
Binary |
Global friend |
Rarely |
friend bool |
operator|| |
Boolean |
function |
|
operator&&(const T& |
|
operators |
recommended |
|
lhs, const T& rhs); |
|
|
|
|
friend bool |
|
|
|
|
operator||(const T& |
|
|
|
|
lhs, const T& rhs); |
operator[] |
Subscripting |
Method |
When you |
E& operator[](int); |
|
(array index) |
required |
want to |
|
|
operator |
|
support |
const E& |
|
|
|
subscripting: |
operator[](int) |
|
|
|
in array-like |
const; |
|
|
|
classes |
|
operator() |
Function call |
Method |
When you |
Return type and |
|
operator |
required |
want objects |
arguments can vary; see |
|
|
|
to behave like |
examples in this chapter |
|
|
|
function |
|
|
|
|
pointers |
|
operator new |
Memory |
Method |
When you |
void* operator |
operator new[] |
allocation |
recommended |
want to |
new(size_t size) |
|
routines |
|
control |
throw(bad_alloc); |
|
|
|
memory |
|
|
|
|
allocation for |
void* operator |
|
|
|
your classes |
new[](size_t size) |
|
|
|
(rarely) |
throw(bad_alloc); |
|
|
|
|
|
Table continued on following page
437