I'am trying to make my own "String" class. But I have problems with overloading operator+. I made operator += that works good and friend operator+ that sometimes does not work as I plan.
String()
{
length = 0;
p = new char[1];
p[0] = '\0';
}
String(const char*s)
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;
}