【问题标题】:Overload string operator+重载字符串运算符+
【发布时间】: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 已触发断点。我应该纠正什么? /////我解决了重载操作符的问题=谢谢!

【问题讨论】:

  • 你考虑过thiss1是同一个字符串的情况
  • temp1 += s1; 更改为temp1 += s2;
  • @songyuanyao 你的错字是对的,但这并不能解释“断点”(我想是段错误)。 Vladislav,您能否提供minimal reproducible example 并向我们展示有关您遇到的错误的更多详细信息?根据有限的信息,我最好的猜测是您的问题的原因超出了您向我们展示的代码。
  • @EdHeal 是正确的。 strcat(p, s1.p) s1 失败 == 因为 s1.p 已被删除。
  • @Vladislav 您应该在问题中提供minimal reproducible example。仅在评论中提供 pastebin 链接并不能改善您的问题。当它保持当前形式时,预计会被删除。

标签: c++ overloading


【解决方案1】:
String operator+=(const String&s1)
{
    int temp_length = length + s1.length;
    String temp(*this);
    length = temp_length;
    delete[]p;
    p = new char[length + 1];
    strcpy(p, temp.p);
    strcat(p, s1.p); //<-- This is the problem
    return *this;
}

friend String operator+(const String &s1, const String &s2) 
{
    String temp1(s1);
    temp1 += s1;
    return temp1;
}

在上面标记的行中,您访问的是s1.p,在您描述为问题的情况下,这与this.p 相同。严格禁止为两个参数调用具有相同数组的 strcat。您需要再制作一份副本。

see this answer

根据strcat(3):

strcat() 函数将 src 字符串附加到 dest 字符串,覆盖 dest 末尾的终止空字节 ('\0'),然后添加一个终止空字节。 字符串不能重叠,且dest字符串必须有足够的空间存放结果。

建议的解决方案:

String operator+=(const String&s1)
{
    int temp_length = length + s1.length;
    String temp(*this);
    length = temp_length;
    delete[]p;
    p = new char[length + 1];
    strcpy(p, temp.p);
    if(p == s1.p)
    {
        String other_temp(s1.p);
        strcat(p, other_temp);
    } else
        strcat(p, s1.p); //<-- no longer a problem
    return *this;
}

friend String operator+(const String &s1, const String &s2) 
{
    String temp1(s1);
    temp1 += s1;
    return temp1;
}

【讨论】:

  • 谢谢!我和你一样重载了 operator=。现在它可以正常工作了
  • 请接受答案,或者如果您仍然认为它不够,请告诉我您需要什么才能认为它是可以接受的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 2017-11-04
  • 2012-09-24
相关资源
最近更新 更多