< previous page page_322 next page >

Page 322
Containment
As you have seen in previous examples, it is possible for the member data of a class to include objects of another class. C++ programmers say that the outer class contains the inner class. Therefore, an Employee class might contain string objects (for the name of the employee) as well as integers (for the employee's salary), and so forth.
Listing 20.3 is a stripped-down but useful String class.
LISTING 20.3 THEString CLASS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     #include <iostream.h>
2:     #include <string.h>
3:
4:     class String
5:     {
6:     public:
7:        // constructors
8:        String();
9:        String(const char *const);
10:       String(const String &);
11:       ~String();
12:
13:       // overloaded operators
14:       char & operator[](int offset);
15:       char operator[](int offset) const;
16:       String operator+(const String&);
17:       void operator+=(const String&);
18:       String & operator= (const String &);
19:
20:       // General accessors
21:       int GetLen()const { return itsLen; }
22:       const char * GetString() const { return itsString; }
23:        static int ConstructorCount;
24:
25:    private:
26:       String (int);         // private constructor
27:       char * itsString;
28:       int itsLen;
29:
30:    };
31:
32:    // default constructor creates string of 0 bytes
33:    String::String()
34:    {
35:       itsString = new char[1];
36:       itsString[0] = \0;
37:       itsLen=0;
38:       // cout << \tDefault string constructor\n;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_322 next page >

If you like this book, buy it!