Sams Teach Yourself C++ in 21 Days

(singke) #1
69: // copy constructor
70: String::String (const String & rhs)
71: {
72: itsLen=rhs.GetLen();
73: itsString = new char[itsLen+1];
74: for (int i = 0; i<itsLen;i++)
75: itsString[i] = rhs[i];
76: itsString[itsLen] = ‘\0’;
77: // cout << “\tString(String&) constructor\n”;
78: // ConstructorCount++;
79: }
80:
81: // destructor, frees allocated memory
82: String::~String ()
83: {
84: delete [] itsString;
85: itsLen = 0;
86: // cout << “\tString destructor\n”;
87: }
88:
89: // operator equals, frees existing memory
90: // then copies string and size
91: String& String::operator=(const String & rhs)
92: {
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=\n”;
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

540 Day 16


LISTING16.1 continued
Free download pdf