Sams Teach Yourself C++ in 21 Days

(singke) #1
the existing string is established by a call to the standard Stringlibrary function
strlen().
On line 28, another constructor,String(unsigned short), is declared to be a private
member function. It is the intent of the designer of this class that no client class ever cre-
ate a Stringof arbitrary length. This constructor exists only to help in the internal cre-
ation of Strings as required, for example, by operator+=, on line 131. This is discussed
in depth when operator+=is described later.
On lines 44–50, you can see that the String(unsigned short)constructor fills every
member of its array with a null character (‘\0’). Therefore, the forloop checks for
i<=lenrather than i<len.
The destructor, implemented on lines 73–77, deletes the character string maintained by
the class. Be certain to include the brackets in the call to the deleteoperator so that
every member of the array is deleted, instead of only the first.
The assignment operator is overloaded on lines 81–92. This method first checks to see
whether the right-hand side of the assignment is the same as the left-hand side. If it isn’t,
the current string is deleted, and the new string is created and copied into place. A refer-
ence is returned to facilitate stacked assignments such as
String1 = String2 = String3;
Another overloaded operator is the offset operator. This operator is overloaded twice,
first on lines 97–103 and again on lines 107–113. Rudimentary bounds checking is per-
formed both times. If the user attempts to access a character at a location beyond the end
of the array, the last character—that is,len-1—is returned.
Lines 117–127 implement the overloading of the operator plus (+) as a concatenation
operator. It is convenient to be able to write
String3 = String1 + String2;
and have String3be the concatenation of the other two strings. To accomplish this, the
operator plus function computes the combined length of the two strings and creates a
temporary string temp. This invokes the private constructor, which takes an integer, and
creates a string filled with nulls. The nulls are then replaced by the contents of the two
strings. The left-hand side string (*this) is copied first, followed by the right-hand side
string (rhs). The first forloop counts through the string on the left-hand side and adds
each character to the new string. The second forloop counts through the right-hand side.
Note that icontinues to count the place for the new string, even as jcounts into the rhs
string.

442 Day 13

Free download pdf