10.4 Overloading Binary Operators

A binary operator can be overloaded as a non-static member function with one parameter or as a non-member function with two parameters (one of those parameters must be either a class object or a reference to a class object). A non-member operator function often is declared as friend of a class for performance reasons.

Binary Overloaded Operators as Member Functions

Consider using < to compare two objects of a String class that you define. When overloading binary operator < as a non-static member function, if y and z are String-class objects, then y < z is treated by the compiler as if y.operator<(z) had been written, invoking the operator< member function with one argument declared below:

class String {  ...

Get C++ How to Program, 10/e 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.