|
|
What if we want to insert a value of class type?
Inserters can be declared for classes and values of class type and used with exactly the same syntax as inserters for the primitive types. That is, assuming the proper declarations and definitions, the examples from the previous subtopic can be used when x or y are variables with class types.
The simplest kinds of examples are provided by a struct that contains a few values.
struct Pair { int x ; int y ; } ;
We want to insert such values into an
ostream,
so we define:
ostream& operator<<(ostream& o, Pair p) {
return o << p.x << " " << p.y ;
}
This operator inserts two integral values (separated by a space)
contained in
p
into
o,
and then returns a reference to
o.
The pattern of taking an ostream& as its first argument and returning the same ostream is what makes it possible for insertions to be strung together conveniently.
As a slightly more elaborate example, consider the following class, which is assumed to implement a variable size vector:
class Vec {
private:
...
public:
Vec() ;
int size() ;
void resize(int) ;
float& operator[](int) ;
...
} ;
We imagine that
Vec
has a current
size,
which may be modified
by
resize,
and that access to individual (float) elements of the
vector is supplied by the subscript operator.
We want to insert
Vec
values into an
ostream,
so we declare:
ostream& operator<< (ostream& o, const Vec& v) ;The definition of this operator is given below. Using Vec& rather than Vec as the type of the second argument avoids some unnecessary copying, which in this case might be expensive. Of course, using Vec* would have a similar advantage in terms of performance, but would obscure the fact that it is the value of the Vec itself that is being output, and not the pointer.
The definition might be:
ostream& operator<< (ostream& o, const Vec& v)
{
o << "[" ; // prefix
for ( int x = 0 ; x < v.size() ; ++x )
// use comma as separator
if ( x!=0 ) o << ',' ;
o << v[x] ;
}
return o << "]" ; // suffix
}
This will output the list as a comma separated list of numbers
surrounded by brackets.
The code takes care to get the empty list right and to avoid a
trailing comma.