69: // Converts a character array to a String
70: String::String(const char * const cString)
71: {
72: itsLen = strlen(cString);
73: itsString = new char[itsLen+1];
74: for (int i = 0; i < itsLen; i++)
75: itsString[i] = cString[i];
76: itsString[itsLen]=’\0’;
77: ASSERT(Invariants());
78: }
79:
80: // copy constructor
81: String::String (const String & rhs)
82: {
83: itsLen=rhs.GetLen();
84: itsString = new char[itsLen+1];
85: for (int i = 0; i < itsLen;i++)
86: itsString[i] = rhs[i];
87: itsString[itsLen] = ‘\0’;
88: ASSERT(Invariants());
89: }
90:
91: // destructor, frees allocated memory
92: String::~String ()
93: {
94: ASSERT(Invariants());
95: delete [] itsString;
96: itsLen = 0;
97: }
98:
99: // operator equals, frees existing memory
100: // then copies string and size
101: String& String::operator=(const String & rhs)
102: {
103: ASSERT(Invariants());
104: if (this == &rhs)
105: return *this;
106: delete [] itsString;
107: itsLen=rhs.GetLen();
108: itsString = new char[itsLen+1];
109: for (int i = 0; i < itsLen;i++)
110: itsString[i] = rhs[i];
111: itsString[itsLen] = ‘\0’;
112: ASSERT(Invariants());
113: return *this;
114: }
115:
116: //non constant offset operator
766 Day 21
LISTING21.4 continued