The Constructors and Destructors. McGraw-Hill The Complete Reference Fourth Edition
जाहिरात
जाहिरात
938
C + + : T h e C o m p l e t e R e f e r e n c e
The private part of StrType contains only two items: p and size. When a string object is created, memory to hold the string is dynamically allocated by using new, and a pointer to that memory is put in p. The string pointed to by p will be a normal, nullterminated character array. Although it is not technically necessary, the size of the string is held in size. Because the string pointed to by p is a null-terminated string, it would be possible to compute the size of the string each time it is needed. However, as you will see, this value is used so often by the StrType member functions that the repeated calls to strlen( ) cannot be justified.
The next several sections detail how the StrType class works.
The Constructors and Destructors
A StrType object may be declared in three different ways: without any initialization, with a quoted string as an initializer, or with a StrType object as an initializer. The constructors that support these three operations are shown here:
// No explicit initialization.
StrType::StrType() { size = 1; // make room for null terminator try { p = new char[size];
} catch (bad_alloc xa) { cout << "Allocation error\n"; exit(1);
} strcpy(p, "");
}
// Initialize using a quoted string.
StrType::StrType(char *str) { size = strlen(str) + 1; // make room for null terminator try { p = new char[size];
} catch (bad_alloc xa) { cout << "Allocation error\n"; exit(1);
} strcpy(p, str);
}
// Initialize using a StrType object.
StrType::StrType(const StrType &o) {
डाउनलोड
जाहिरात