when + is overloaded as a member function, the class object (in this case, 'string') is always on the left side. If you want to put 'string' on the right side, you need to make a global function that overloads +. These functions are sometimes declared as friends of the class, but I find that unnecessary, as you can usually stick to public stuff. See code below.
Also, you need to return a 'string', not a 'string&' from the + operator. The reason why is because you're returning a temporary object, and that object loses scope (dies) as soon as the function returns, which means the reference returned is bad (because the object it points to no longer exists).
And of course, returning a string value instead of a string& reference means you need a copy constructor, which you don't have now.
And ew @ malloc. But whatever works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class string
{
public:
string operator + (const char* str) const
{
string temp(*this); // uses copy ctor
// append 'str' to 'temp' here
return temp; // uses copy ctor
}
};
static string operator + (const char* l,const string& r)
{
return string(l) + r; // uses a ctor which accepts a 'const char*' initializer
// also uses a operator + which has 'string' on both left and right side
}
| |
Note that copying full strings every time you need to call the copy ctor (which is often) is inefficient. As such, common practice in string objects is to 'share' string data with other string objects, keeping track of how many strings are accessing the string data with a
reference count. When one string needs to change the string data, it checks to see if it's sharing data with any other strings (by checking the reference count). If it is sharing, it makes a unique copy of the string so that it's no longer sharing and modifies that.
You don't
have to do this, of course. But it's a bit more efficient.