a_j58 2023-10-10 15:32 采纳率: 0%
浏览 14

关于#c++#的问题:我想问一下调试出现这种错误是什么原因,我也检查了将空指针置为空的情况


#include<iostream>
using namespace std;
class MyString
{
private:
    char* str;
public:
    friend MyString operator+(const MyString& d1, const MyString& d2);

    MyString(const char* p) :str(nullptr)
    {
        if (p != nullptr)
        {
            int len = strlen(p) + 1;
            str = new char[len];
            strcpy(str, p);
        }
        else
        {
            str = new char[1];
            *str = '\0';
        }
    }
    MyString() //初始化列表
        : str(nullptr)
    {}
    MyString(const MyString& d)
    {
        str = d.str;
    }
    ~MyString()
    {
        if (str != nullptr)
        {
            delete[] str;
            str = nullptr;
        }
    }
    MyString& operator=(const MyString& other)
    {
        if (this == &other)
        {
            return *this;
        }

        delete[] str;
        int len = strlen(other.str) + 1;
        str = new char[len];
        strcpy(str, other.str);
        return *this;
    }
    void Print()
    {
        cout << str << endl;
    }
};
 MyString operator+(const MyString& d1, const MyString& d2)
{

     int len1 = strlen(d1.str);
     int len2 = strlen(d2.str);
     int newLen = len1 + len2 + 1;

     char* p = new char[newLen];
     strcpy(p , d1.str);
     strcat(p , d2.str);
     MyString temp;

     temp.str = p;
     return temp;
 }

int main()
{
    MyString s1("yhpin");
    MyString s2(s1);
    MyString s3;
    s3 = s1 + s2;
    s3.Print();
    s3 = s1 + "hello";
    s3.Print();
    s3 = "hello" + s1;
    s3.Print();
    return 0;
}

img

img


我想问一下调试出现这种错误是什么原因,我也检查了将空指针置为空的情况,求各位解答一下

  • 写回答

2条回答 默认 最新

  • yun6853992 2023-10-10 15:52
    关注

    在函数执行结束,必然执行析构函数,那么析构函数代码中对应的delete是不是一定要new过
    那么 你这里的构造函数,是不是和析构不对应?

    img


    你可以吧main函数中相关内容注释进行测试,调试试试

    评论

报告相同问题?

问题事件

  • 创建了问题 10月10日

悬赏问题

  • ¥15 如何用python读取nasa电池数据集?
  • ¥50 MTK手机模拟HID鼠标出现卡顿
  • ¥20 求下下面这个数据结构代码
  • ¥15 路由器考试怎么办,有懂行的吗 ,eNSP
  • ¥20 前端 二进制文件流图片转化异常
  • ¥15 github上的这个C语言项目如何跑起来
  • ¥15 java 判断某个数 区间是否存在
  • ¥15 appium控制多个雷电模拟器问题
  • ¥15 C# iMobileDevice
  • ¥15 谁会做这个啊#ensp#Boson NetSim