Sams Teach Yourself C++ in 21 Days

(singke) #1
i: 0
i: 2
i: 4
i: 6
i: 8
i: 10
i: 12
i: 14
i: 16
i: 18

Done.
The declaration of the Arraytemplate has been extended to include the friend
function Intrude(). This addition on line 48 declares that every instance of an
int Arrayconsiders Intrude()to be a friend function; thus,Intrude()has access to
the private member data and functions of the Arrayinstance.
The Intrude()function is defined on lines 57–63. On line 60,Intrude()accesses
itsSizedirectly, and on line 61, it accesses pTypedirectly. This trivial use of these
members was unnecessary because the Arrayclass provides public accessors for this
data, but it serves to demonstrate how friend functions can be declared with templates.

General Template Friend Class or Function ..................................................


It would be helpful to add a display operator to the Arrayclass so that values could be
sent to an output steam and treated appropriately based on their type. One approach is to
declare a display operator for each possible type of Array, but this undermines the whole
point of having made Arraya template.
What is needed is an insertion operator that works for any possible type of Array:
ostream& operator<< (ostream&, Array<T>&);
To make this work,operator<<needs to be declared to be a template function:
template <class T>
ostream& operator<< (ostream&, Array<T>&)
Now that operator<<is a template function, you need only to provide an implementa-
tion. Listing 19.4 shows the Arraytemplate extended to include this declaration and pro-
vides the implementation for the operator<<.

LISTING19.4 Using Operator ostream
0: //Listing 19.4 Using Operator ostream
1: #include <iostream>
2: using namespace std;

674 Day 19


ANALYSIS
Free download pdf