【发布时间】:2011-12-08 02:38:10
【问题描述】:
目前我正在尝试为我编写的名为 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;
}
其中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&)
有谁知道如何更改我的代码以实现此功能?
【问题讨论】:
-
s1.data在默认构造函数中初始化为什么(您使用MyString test;调用的内容是什么? -
数据=新字符[1];数据[0] = '\0';长度 = 0;
-
你能发布 MyString 类的完整源代码吗?
-
这个功能没有意义。您希望多个 += 在同一语句中表示什么?这改变了运算符的语义。
-
如果询问某个问题,您应该在问题中包含对该问题的描述。 “不起作用”是最糟糕的问题描述。如果你不说哪里出了问题,你怎么指望有人能够提供帮助?