4.6. Building an Iterator Class
To illustrate how to overload a set of operators for a class, let’s walk through the implementation of an iterator class. We must support the following usage:
Triangular trian( 1, 8 ); Triangular::iterator it = trian.begin(), end_it = trian.end(); while ( it != end_it ) { cout << *it << ' '; ++it; }
For this to work, of course, the operators !=, *, and ++ must be defined for objects of the iterator class. How do we do this? We define them as operator member functions. An operator function looks like an ordinary function except that rather than provide the function with a name, we specify the keyword operator followed by the operator we wish to overload. For example,
class Triangular_iterator { public: ...
Get Essential C++ 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.