Освой самостоятельно С++ за 21 день.
Шрифт:
29: char * itsStnng,
30: unsigned short itsLen
31: }
32:
33: // Конструктор, заданный no умолчанию, создает строку нулевой длины
34: String String
35: {
36: itsStnng = new char[1]
37: itsStrmg[0] = '\0'
38: itsLen=0;
39: }
40:
41: // Закрытый (вспомогательный) конструктор
42: // используется только методами класса для создания
43: // строк требуемой длины с нулевым наполнением
4й: String String(unsigned short len)
45: {
46: itsStnng = new char[len+1]
47: for (unsigned short i = 0 i<=len, i++)
48: itsString[i] = \0 ,
49: itsLen=len,
50: }
51:
52: //
53: String String(const char * const cString)
54: {
55: itsLen = strlen(cString);
56: itsString = new char[itsLen+1];
57: for (unsigned short i = 0; i<itsLen: i++)
58: itsString[i] = cString[i];
59: itsString[itsLen]='\0';
60: }
61:
62: // Конструктор-копировщик
63: String::String (const String & rhs)
64: {
65: itsLen=rhs.GetLen;
66: itsString = new char[itsLen+1];
67: for (unsigned short i = 0; i<itsLen;i++)
68: itsString[i] = rhs[i];
69: itsString[itsLen] = '\0';
70: }
71:
72: // Деструктор для освобождения памяти
73: String::~String
74: {
75: delete [] itsString;
76: itsLen = 0;
77: }
78:
79: // Оператор присваивания освобождает память
80: // и копирует туда string и size
81: String& String::operator=(const String & rhs)
82: {
83: if (this == &rhs)
84: return *this;
85: delete [] itsString;
86: itsLen=rhs.GetLen;
87: itsString = new char[itsLen+1];
88: for (unsigned short i = 0; i<itsLen;i++)
89: itsString[i] = rhs[i];
90: itsString[itsLen] = '\0';
91: return *this;
92: }
93:
94: //неконстантный оператор индексирования
95: // возвращает ссылку на символ так, что его
96: // можно изменить!
97: char & String::operator[](unsigned short offset)
98: {
99: if (offset > itsLen)
100: return itsString[itsLen-1];
101: else
102: return itsString[offset];
103: }
104:
105: // константный оператор индексирования для использования
106: // с константными объектами (см. конструктор-копировщик!)
107: char String::operator[](unsigned short offset) const
108: {
109: if (offset > itsLen)
110: return itsString[itsLen-1];
111: else
112: return itsString[offset];
113: }
114:
115: // создание новой строки путем добавления
116: // текущей строки к rhs
117: String String::operator+(const String& rhs)
118: {
119: unsigned short totalLen = itsLen + rhs.GetLen;
120: String temp(totalLen);
121: unsigned short i;
122: for ( i= 0; i<itsLen; i++)
123: temp[i] = itsString[i];
124: for (unsigned short j = 0; j<rhs.GetLen; j++, i++)
125: temp[i] = rhs[j];
126: temp[totalLen]='\0';
127: return temp;
128: }
129:
130: //
изменяет текущую строку и возвращает void131: void String::operator+=(const String& rhs)
132: {
133: unsigned short rhsLen = rhs.GetLen;
134: unsigned short totalLen = itsLen + rhsLen;
135: String temp(totalLen);
136: unsigned short i;
137: for (i = 0; i<itsLen; i++)
138: temp[i] = itsString[i];
139: for (unsigned short j = 0; j<rhs.GetLen; j++, i++)
140: temp[i] = rhs[i-itsLen];
141: temp[totalLen]='\0';
142: *this = temp;
143: }
144:
145: int main
146: {
147: String s1("initial test");
148: cout << "S1:\t" << s1.GetString << endl;
149:
150: char * temp = "Hello World";
151: s1 = temp;
152: cout << "S1:\t" << s1.GetString << endl;
153:
154: char tempTwo[20];
155: strcpy(tempTwo,"; nice to be here!");
156: s1 += tempTwo;
157: cout << "tempTwo:\t" << tempTwo << endl;
158: cout << "S1:\t" << s1.GetString << endl;
159:
160: cout << "S1[4] :\t" << s1[4] << endl;
161: s1[4]='o';
162: cout << "S1:\t" << s1.GetString << endl;
163:
164: cout << "S1[999] :\t" << s1[999] << endl;
165:
166: String s2(" Another string");
167: String s3;
168: s3 = s1+s2;
169: cout << "S3:\t" << s3.GetString << endl:
170:
171: String s4;
172: s4 = "Why does this work?";
173: cout << "S4:\t" << s4.GetString << endl;
174: return 0;
175: }
Результат:
S1: initial test
S1: Hello world
tempTwo: ; nice to be here!
S1: Hello world; nice to be here!
S1[4]: o
S1: Hello World; nice to be here!
S1[999]: !
S3: Hello World; nice to be here! Another string
S4: Why does this work?
Анализ: В строках 7—31 объявляется простой класс String. В строках 11—13 объявляются конструктор по умолчанию, конструктор-копировщик и конструктор для приема существующей строки с концевым нулевым символом (стиль языка С).