#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;
}
我想问一下调试出现这种错误是什么原因,我也检查了将空指针置为空的情况,求各位解答一下