Sams Teach Yourself C++ in 21 Days

(singke) #1
Advanced Inheritance 541

16


117: // on const objects (see copy constructor!)
118: char String::operator[](int offset) const
119: {
120: if (offset > itsLen)
121: return itsString[itsLen-1];
122: else
123: return itsString[offset];
124: }
125:
126: // creates a new string by adding current
127: // string to rhs
128: String String::operator+(const String& rhs)
129: {
130: int totalLen = itsLen + rhs.GetLen();
131: String temp(totalLen);
132: int i, j;
133: for (i = 0; i<itsLen; i++)
134: temp[i] = itsString[i];
135: for (j = 0; j<rhs.GetLen(); j++, i++)
136: temp[i] = rhs[j];
137: temp[totalLen]=’\0’;
138: return temp;
139: }
140:
141: // changes current string, returns nothing
142: void String::operator+=(const String& rhs)
143: {
144: unsigned short rhsLen = rhs.GetLen();
145: unsigned short totalLen = itsLen + rhsLen;
146: String temp(totalLen);
147: int i, j;
148: for (i = 0; i<itsLen; i++)
149: temp[i] = itsString[i];
150: for (j = 0; j<rhs.GetLen(); j++, i++)
151: temp[i] = rhs[i-itsLen];
152: temp[totalLen]=’\0’;
153: *this = temp;
154: }
155:
156: // int String::ConstructorCount = 0;

Put the code from Listing 16.1 into a file called MyString.hpp. Then, any
time you need the Stringclass, you can include Listing 16.1 by using
#include “MyString.hpp”, such as in this listing. You might notice a number
of commented lines in this listing. The purpose of these lines are explained
throughout today’s lesson.

NOTE


LISTING16.1 continued

Free download pdf