I have created an operator+ function for my class string, but I have a problem related to the direction of the assignement:
My function is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
String& String::operator+(const String& other)
{
Append(other.ptr);//Append is just a function that internally
//creates a new pointer and copies the old sequence of characters
//+ the new one in the new pointer
return *this;
}
/*Suppose this are all instances of my class String. What happens here first is the
addition of str2 + str3, then (str2 + str3) + str2 and finally (str2 + str3) + str2)
+ str2. This means that the assignment is done from left to the right, going to
the opposite direction than usual. This is not of course what I want, and therefore
this is of course my problem. In this situation I have also to return a
non-constant String&. If there were just to operands on the right of =, there
wouldn't be a problem and I could also return a const String&, but this is not the
problem.*/
str1 = str2 + str3 + str2 + str2;
What you wrote would be correct if it were called operator+=. operator+ always returns by value, because it creates a *new* object, that is a sum of left and right.
zwilu wrote:
from left to the right, going to the opposite direction than usual
First of all, you are not supposed to modify the current String in operator+.
What you have written is in essence operator+=.
operator+ is supposed to return a temporary String, and not a reference to the current and modified String.
1 2 3 4 5 6 7
String operator + (const String &lhs, const String &rhs)
{
String temp(lhs); // assuming you wrote a copy-constructor
temp.Append(rhs.ptr);
return temp;
}
Second of all, it is good practice to overload operator+ as a non-member function.
This is because by overloading it as member function, you force the left hand side operand to be a String. This will be an annoyance in cases where the lhs operand isn't a String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
String String::operator + (constchar *rhs)
{
// ...
}
String temp("part");
String s1 = temp + "one"; // works
String s2 = "second" + temp; // doesn't work
String operator + (constchar *lhs, const String &rhs)
{
// ...
}
String s3 = "third" + temp; // now this works
I created this overload as internal function: String operator+(const String& other);, because the compiler was telling me that, when I write this instruction str1 = str1 + str2, there was no String operator+(const String& other), but actually I haven't understood why is not possible to write String operator + (const String &lhs, const String &rhs), as you did.