Managing Arrays and Strings 441
13
S1: initial test
S1: Hello World
tempTwo: ; nice to be here!
S1: Hello World; nice to be here!
S1[4]: o
S1: Hellx World; nice to be here!
S1[999]:!
S3: Hellx World; nice to be here! Another string
S4: Why does this work?
Your Stringclass’s declaration is on lines 7–31. To add flexibility to the class,
there are three constructors in lines 11–13: the default constructor, the copy con-
structor, and a constructor that takes an existing null-terminated (C-style) string.
To allow the your users to manipulate strings easily, this Stringclass overloads several
operators including the offset operator ([ ]), operator plus (+), and operator plus-equals
(+=). The offset operator is overloaded twice: once as a constant function returning a
charand again as a nonconstant function returning a reference to a char.
The nonconstant version is used in statements such as
S1[4]=’x’;
as seen on line 161. This enables direct access to each of the characters in the string.
A reference to the character is returned so that the calling function can manipulate it.
The constant version is used when a constant Stringobject is being accessed, such as in
the implementation of the copy constructor starting on line 63. Note that rhs[i]is
accessed, yet rhsis declared as a const String &. It isn’t legal to access this object by
using a nonconstant member function. Therefore, the offset operator must be overloaded
with a constant accessor. If the object being returned were large, you might want to
declare the return value to be a constant reference. However, because a charis only one
byte, there would be no point in doing that.
The default constructor is implemented on lines 34–39. It creates a string whose length is
- It is the convention of this Stringclass to report its length not counting the terminat-
ing null. This default string contains only a terminating null.
The copy constructor is implemented on lines 63–70. This constructor sets the new
string’s length to that of the existing string—plus one for the terminating null. It copies
each character from the existing string to the new string, and it null-terminates the new
string. Remember that, unlike assignment operators, copy constructors do not need to test
if the string being copied into this new object is itself—that can never happen.
Stepping back, you see in lines 53–60 the implementation of the constructor that takes an
existing C-style string. This constructor is similar to the copy constructor. The length of
OUTPUT
ANALYSIS