Sams Teach Yourself C++ in 21 Days

(singke) #1
What you would like to do is write this:
cout << theString;
To accomplish this, you must override operator<<(). Day 17, “Working with Streams,”
presents the ins and outs (cins and couts?) of working with iostreams; for now, Listing
16.9 illustrates how operator<<can be overloaded using a friend function.

LISTING16.9 Overloading operator<<()
0: // Listing 16.9 Overloading operator<<()
1:
2: #include <iostream>
3: #include <string.h>
4: using namespace std;
5:
6: class String
7: {
8: public:
9: // constructors
10: String();
11: String(const char *const);
12: String(const String &);
13: ~String();
14:
15: // overloaded operators
16: char & operator[](int offset);
17: char operator[](int offset) const;
18: String operator+(const String&);
19: void operator+=(const String&);
20: String & operator= (const String &);
21: friend ostream& operator<<
22: ( ostream& theStream,String& theString);
23: // General accessors
24: int GetLen()const { return itsLen; }
25: const char * GetString() const { return itsString; }
26:
27: private:
28: String (int); // private constructor
29: char * itsString;
30: unsigned short itsLen;
31: };
32:
33:
34: // default constructor creates string of 0 bytes
35: String::String()
36: {
37: itsString = new char[1];
38: itsString[0] = ‘\0’;
39: itsLen=0;
40: // cout << “\tDefault string constructor” << endl;

586 Day 16

Free download pdf