Sams Teach Yourself C++ in 21 Days

(singke) #1
What’s Next 765

21


21: typedef int BOOL;
22:
23:
24: class String
25: {
26: public:
27: // constructors
28: String();
29: String(const char *const);
30: String(const String &);
31: ~String();
32:
33: char & operator[](int offset);
34: char operator[](int offset) const;
35:
36: String & operator= (const String &);
37: int GetLen()const { return itsLen; }
38: const char * GetString() const { return itsString; }
39: BOOL Invariants() const;
40:
41: private:
42: String (int); // private constructor
43: char * itsString;
44: // unsigned short itsLen;
45: int itsLen;
46: };
47:
48: // default constructor creates string of 0 bytes
49: String::String()
50: {
51: itsString = new char[1];
52: itsString[0] = ‘\0’;
53: itsLen=0;
54: ASSERT(Invariants());
55: }
56:
57: // private (helper) constructor, used only by
58: // class methods for creating a new string of
59: // required size. Null filled.
60: String::String(int len)
61: {
62: itsString = new char[len+1];
63: for (int i = 0; i <= len; i++)
64: itsString[i] = ‘\0’;
65: itsLen=len;
66: ASSERT(Invariants());
67: }
68:

LISTING21.4 continued

Free download pdf