【发布时间】:2016-05-01 14:08:34
【问题描述】:
我正在尝试制作自己的“字符串”类。但是我有重载运算符+的问题。我让 operator += 工作得很好,而 operator+ 有时不能按我的计划工作。
String()
{
length = 0;
p = new char[1];
p[0] = '\0';
}
String(const char*s)
{
length = strlen(s);
p = new char[length+1];
strcpy(p, s);
}
String(const String& s)
{
if (this != &s)
{
length = s.length;
p = new char[s.length + 1];
strcpy(p, s.p);
}
}
~String()
{
delete[]p;
};
String &operator+=(const String&s1)
{
String temp;
temp.length = length + s1.length;
delete[]temp.p;
temp.p = new char[temp.length + 1];
strcpy(temp.p, p);
strcat(temp.p, s1.p);
length = temp.length;
delete[]p;
p = new char[length + 1];
strcpy(p, temp.p);
return *this;
}
friend String operator+(const String &s1, const String &s2)
{
String temp1(s1);
temp1 += s2;
return temp1;
}
如果我像这样使用运算符 +: String c =a+b;一切都按计划进行,但如果我写 a=a+b;我收到错误 String.exe 已触发断点。我应该纠正什么? /////我解决了重载操作符的问题=谢谢!
【问题讨论】:
-
你考虑过
this和s1是同一个字符串的情况 -
将
temp1 += s1;更改为temp1 += s2;。 -
@songyuanyao 你的错字是对的,但这并不能解释“断点”(我想是段错误)。 Vladislav,您能否提供minimal reproducible example 并向我们展示有关您遇到的错误的更多详细信息?根据有限的信息,我最好的猜测是您的问题的原因超出了您向我们展示的代码。
-
@EdHeal 是正确的。
strcat(p, s1.p)s1 失败 == 因为 s1.p 已被删除。 -
@Vladislav 您应该在问题中提供minimal reproducible example。仅在评论中提供 pastebin 链接并不能改善您的问题。当它保持当前形式时,预计会被删除。
标签: c++ overloading