目前我正在尝试为我编写的名为mystring的类重写+=运算符:
其中 length 是字符串的长度,data 是以 char* 格式存储的字符串。
当我尝试像下面这样做时,程序可以正常工作:
但是当我尝试类似这样的东西时,它不起作用:
基本上,当我交替使用“+=”和“+”混合时它不起作用。以下是编译时的错误信息:
有人知道我该如何更改我的代码才能实现这个功能吗?
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;
}
其中 length 是字符串的长度,data 是以 char* 格式存储的字符串。
当我尝试像下面这样做时,程序可以正常工作:
MyString test1 = "hi";
MyString test2 = "to";
test1 += test2;
但是当我尝试类似这样的东西时,它不起作用:
MyString test;
MyString test1 = "hi";
MyString test2 = "to";
test += test2 + test1
+= "you";
基本上,当我交替使用“+=”和“+”混合时它不起作用。以下是编译时的错误信息:
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&)
有人知道我该如何更改我的代码才能实现这个功能吗?