moon19961996 2019-04-12 16:05 采纳率: 66.7%
浏览 407
已采纳

运算符重载之后,析构函数报错,怎么改?顺便说一下原因,谢谢

 class String
{
public:

    String(const char* a=NULL);
    String(const String&a);
    ~String();
    void operator=(const char* a);
    void operator=(String &a);
    String operator+(const char* a);
    String operator+(String a);
    void operator<(const char* a);
    void operator<(String a);
    void operator>(const char* a);
    void operator>(String a);
    void print();

private:
    char *m_str;
};

String String::operator+(const char* a)
 {
    String c;
    c.m_str = new char[strlen(a) + strlen(m_str) + 1];
    int i = 0;
    for (; i < strlen(m_str); i++)
    {
        c.m_str[i] = m_str[i];
    }
    for (int t = 0; t < strlen(a); t++)
    {
        c.m_str[i] = a[t];
    }

    return c;
 }

String String::operator+(String a)
 {
    String c;
    c.m_str = new char[strlen(a.m_str) + strlen(m_str) + 1];
    int i = 0;
    for (; i < strlen(m_str); i++)
    {
        c.m_str[i] = m_str[i];
    }

    for (int t = 0; t <=strlen(a.m_str); t++,i++)
    {
        c.m_str[i] = a.m_str[t];
    }


    return c;
 }

 void String::operator<(const char* a)
 {

 }

 void String::operator<(String a)
 {

 }

 void String::operator>(const char* a)
 {

 }

 void String::operator>(String a)
 {

 }


 String::String(const char* a)
 {
     if (a == NULL)
     {
         m_str = new char[1];
         m_str[0] = '\0';
     }
     else
     {
         int b = strlen(a);
         m_str = new char[b+1 ];
         strcpy_s(m_str,b+1,a);
     }
 }

 String::String(const String&a)
 {
     int b = strlen(a.m_str);
     m_str = new char[b + 1];
     strcpy_s(m_str, b + 1, a.m_str);
 }

 String::~String()
 {
     printf("析构%s",this->m_str);
     delete[]m_str;
     m_str = NULL;
 }

 void String::operator=(const char* a)
 {
     int b = strlen(a);
     m_str = new char[b + 1];
     strcpy_s(m_str, b + 1, a);
 }

 void String::operator=(String& a)
 {
     int b = strlen(a.m_str);
     m_str = new char[b + 1];
     strcpy_s(m_str, b + 1, a.m_str);
 }


void String::print()
{
    cout<<m_str<<endl;
}

int main()
{
    String s1 = "abc";
    String s2 ("def");
    String s3 =s1;
    String s4 = s1+s3;


    s1.print();
    s2.print();
    s3.print();
    s4.print();

    return 0;
}

String s4 = s1+s3;这一行会调用析构函数,释放内存的时候会弹出系统的debug窗口!
图片说明

  • 写回答

2条回答 默认 最新

  • 窝米逗佛~ 2019-04-12 16:50
    关注

    额,路过看到了,说一下你的错误原因,内存申请的太小,然后又越界使用了 ,最后在释放的时候就出问题了, 改的话...你自己改改看吧 , 不行就等其他人来帮你整了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动