Sams Teach Yourself C++ in 21 Days

(singke) #1
93: if (this == &rhs)
94: return *this;
95: delete [] itsString;
96: itsLen=rhs.GetLen();
97: itsString = new char[itsLen+1];
98: for (int i = 0; i<itsLen;i++)
99: itsString[i] = rhs[i];
100: itsString[itsLen] = ‘\0’;
101: return *this;
102: // cout << “\tString operator=” << endl;
103: }
104:
105: //non constant offset operator, returns
106: // reference to character so it can be
107: // changed!
108: char & String::operator[](int offset)
109: {
110: if (offset > itsLen)
111: return itsString[itsLen-1];
112: else
113: return itsString[offset];
114: }
115:
116: // constant offset operator for use
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)

588 Day 16


LISTING16.9 continued
Free download pdf