This example illustrates a simple vector class. The class defines and constructor, overloads the indexing operator, and defines a stream output (insertor) operator.
The indexing operator returns a reference to a vecotr element so that it can be used on the left hand side of an assignment or as an argument to a function that requires a reference.
The insertor operator is defined as a friend function,
because the left operator is a stream. (In defining the
rational
class, we overloaded the insertor operator
outside of the class. By overloading the operator in the class,
this implementation saves a function call for every use of this
operator.)
// // Vector.C // // A. B. Maccabe 3/10/97 // // A simple vector class -- illustrates overloading the index operator // with array bounds checking // // // this example illustrates a function that returns a reference (and // not a value). // #include <assert.h> #include <iostream.h> class Vector { public: // constructor Vector( int lower, int upper ) { lb = lower; ub = upper; data = new double[upper-lower+1]; }; double& operator[] ( int indx ) { assert( lb<=indx && indx<=ub ); return data[indx-lb]; }; friend ostream& operator << ( ostream &os, Vector v ) { for( int i = v.lb ; i <= v.ub ; i++ ) { os << i << ':' << v.data[i-v.lb] << ' '; } return os; } private: int lb, ub; double *data; }; int main() { Vector v( 10, 20 ); for( int i = 10 ; i <= 20 ; i++ ) { v[i] = i; } cout << v << endl; }