Sams Teach Yourself C++ in 21 Days

(singke) #1
Advanced Inheritance 581

16


What you could not do, however, was create a C-style string (a character string) and add
to it using a string object, as shown in this example:
char cString[] = {“Hello”};
String sString(“ World”);
String sStringTwo = cString + sString; //error!
C-style strings don’t have an overloaded operator+. As discussed on Day 10, “Working
with Advanced Functions,” when you say cString + sString;what you are really call-
ing is cString.operator+(sString). Because you can’t call operator+()on a C-style
string, this causes a compile-time error.
You can solve this problem by declaring a friendfunction in String, which overloads
operator+but takes two string objects. The C-style string is converted to a string object
by the appropriate constructor, and then operator+is called using the two string objects.
To clarify this, take a look at Listing 16.8.

LISTING16.8 Friendly operator+


0: //Listing 16.8 - friendly operators
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[](int offset);
18: char operator[](int offset) const;
19: String operator+(const String&);
20: friend String operator+(const String&, const String&);
21: void operator+=(const String&);
22: String & operator= (const String &);
23:
24: // General accessors
25: int GetLen()const { return itsLen; }
26: const char * GetString() const { return itsString; }
27:
28: private:
Free download pdf