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?