Advanced Inheritance 585
16
s1: String One
s2: String Two
c1: C-String One
s3: String One String Two
s4: String One C-String One
s5: C-String One String Two
The implementation of all the string methods except operator+are unchanged
from Listing 16.1. On line 20, a new operator+is overloaded to take two con-
stant string references and to return a string, and this function is declared to be a friend.
Note that this operator+is not a member function of this or any other class. It is
declared within the declaration of the Stringclass only so that it can be made a friend,
but because it is declared, no other function prototype is needed.
The implementation of this operator+is on lines 143–154. Note that it is similar to the
earlier operator+, except that it takes two strings and accesses them both through their
public accessor methods.
The driver program demonstrates the use of this function on line 172, where operator+
is now called on a C-style string!
OUTPUT
ANALYSIS
Friend Functions
Declare a function to be a friend by using the keyword friendand then the full specification
of the function. Declaring a function to be a friend does not give the friendfunction access to
your thispointer, but it does provide full access to all private and protected member data and
functions.
Example
class PartNode
{ // ...
// make another class’s member function a _friend
friend void PartsList::Insert(Part *);
// make a global function a friend
friend int SomeFunction();
// ...
};
Overloading the Insertion Operator ....................................................................
You are finally ready to give your Stringclass the capability to use coutthe same as
any other type. Until now, when you’ve wanted to print a string, you’ve been forced to
write the following:
cout << theString.GetString();