Currently I’m trying to rewrite the += operator for a class I wrote called mystring:
MyString& operator+=(MyString& s1, const MyString& s2)
{
int newStringLength = s1.length + s2.length;
char* newStorage = new char[newStringLength + 1];
strcpy(newStorage, s1.data);
strcpy(newStorage + s1.length, s2.data);
delete[] s1.data;
s1.length = newStringLength;
s1.data = newStorage;
return s1;
}
MyString operator+(const MyString& s1, const MyString& s2)
{
MyString temp;
delete[] temp.data;
temp.length = s1.length;
temp.data = new char[temp.length+1];
strcpy(temp.data, s1.data);
temp+=s2;
return temp;
}
Where length is the length of the string and data is a string stored in char * format.
The program works fine when I try to do something like:
MyString test1 = "hi";
MyString test2 = "to";
test1 += test2;
But does not work when I try something like:
MyString test;
MyString test1 = "hi";
MyString test2 = "to";
test += test2 + test1
+= "you";
Basically when I start mixing += and + in an alternating way it doesn’t work. Here is the error at compilation:
testoutput.cpp:26: error: no match for ‘operator+=’ in ‘operator+(const MyString&, const MyString&)(((const MyString&)((const MyString*)(& test1)))) += "you"’
mystring.h:45: note: candidates are: MyString& operator+=(MyString&, const MyString&)
Does anyone have any idea how I can change my code in order to achieve this functionality?
It doesn’t make sense to mix
+and+=in such a way. I’m not really sure what your intended behavior is, but if you want the nested+=to apply totest1, you’ll have to use parenthesis:This is not a problem with your assignment operator, but with operator precedence in the language. If you would replace
MyStringwithintyou would run into the same problems.The precedence and associativity of the
+and+=operators causes the expression without parenthesis to be interpreted like this:This tries to assign to
test2 + test1, but that’s not possible (you can only assign to variables). This operator precedence cannot be changed and without parenthesis the expression will always be interpreted this way.