Managing Arrays and Strings 437
13
Before using this class, you will create a custom Stringclass as an exercise in under-
standing the issues involved. At a minimum, your Stringclass should overcome the
basic limitations of character arrays.
Like all arrays, character arrays are static. You define how large they are. They always
take up that much room in memory, even if you don’t need it all. Writing past the end of
the array is disastrous.
A good Stringclass allocates only as much memory as it needs and always enough to
hold whatever it is given. If it can’t allocate enough memory, it should fail gracefully.
Listing 13.14 provides a first approximation of a Stringclass.
This custom Stringclass is quite limited and is by no means complete,
robust, or ready for commercial use. That is fine, however, as the Standard
Library does provide a complete and robust Stringclass.
NOTE
LISTING13.14 Using a Stringclass
0: //Listing 13.14 Using a String class
1:
2: #include <iostream>
3: #include <string.h>
4: using namespace std;
5:
6: // Rudimentary string class
7: class String
8: {
9: public:
10: // constructors
11: String();
12: String(const char *const);
13: String(const String &);
14: ~String();
15:
16: // overloaded operators
17: char & operator[](unsigned short offset);
18: char operator[](unsigned short offset) const;
19: String operator+(const String&);
20: void operator+=(const String&);
21: String & operator= (const String &);
22:
23: // General accessors
24: unsigned short GetLen()const { return itsLen; }
25: const char * GetString() const { return itsString; }
26:
27: private: