Sams Teach Yourself C++ in 21 Days

(singke) #1
Managing Arrays and Strings 443

13


On line 127, operator plus returns the string,temp, by value, which is assigned to the
string on the left-hand side of the assignment (string1). On lines 131–143, operator +=
operates on the existing string—that is, the left-hand side of the statement string1 +=
string2. It works the same as operator plus, except that the temporary value,temp,is
assigned to the current string (*this = temp) on line 142.


The main()function (lines 145–175) acts as a test driver program for this class. Line 147
creates a Stringobject by using the constructor that takes a null-terminated C-style
string. Line 148 prints its contents by using the accessor function GetString(). Line 150
creates a second C-style string, which is assigned on line 151 to the original string,s1.
Line 152 prints the result of this assignment, thus showing that the overloading of the
assignment operator truly does work.


Line 154 creates a third C-style string called tempTwo. Line 155 invokes strcpy()to fill
the buffer with the characters ; nice to be here!Line 156 invokes the overloaded
operator +=in order to concatenate tempTwoonto the existing string s1. Line 158 prints
the results.


On line 160, the fifth character in s1is accessed using the overloaded offset operator.
This value is printed. On line 161, a new value of ‘x’ is assigned to this character within
the string. This invokes the nonconstant offset operator ([ ]). Line 162 prints the result,
which shows that the actual value has, in fact, been changed.


Line 164 attempts to access a character beyond the end of the array. From the informa-
tion printed, you can see that the last character of the array is returned, as designed.


Lines 166 and 167 create two more Stringobjects, and line 168 calls the addition opera-
tor. Line 169 prints the results.


Line 171 creates a new Stringobject,s4. Line 172 uses the overloaded assignment
operator to assign a literal C-style string to s4. Line 173 prints the results. You might be
thinking, “The assignment operator is defined to take a constant Stringreference on line
21, but here the program passes in a C-style string. Why is this legal?”


The answer is that the compiler expects a String, but it is given a character array.
Therefore, it checks whether it can create a Stringfrom what it is given. On line 12, you
declared a constructor that creates Stringsfrom character arrays. The compiler creates a
temporary Stringfrom the character array and passes it to the assignment operator. This
is known as implicit casting, or promotion. If you had not declared—and provided the
implementation for—the constructor that takes a character array, this assignment would
have generated a compiler error.

Free download pdf