#include <iostream>
struct String
{
public:
String();
String(const char *str);
String(const String& str);
void print();
~String();
String& operator=(const String& other);
String operator+(const String& other);
private:
char *str;
int lenght;
};
String::String()
{
this->str = nullptr;
lenght = 0;
}
String::String(const char *str)
{
lenght = strlen(str);
this->str = new char[lenght + 1];
for(int i = 0; i < lenght; i++)
{
this->str[i] = str[i];
}
this->str[lenght] = '\0';
}
String::String(const String& other)
{
lenght = other.lenght;
this->str = new char[lenght + 1];
for (int i = 0; i < lenght; i++)
{
this->str[i] = other.str[i];
}
this->str[other.lenght] = '\0';
}
void String::print()
{
std::cout << str;
}
String::~String()
{
delete[] this->str;
this->str = nullptr;
}
String& String::operator=(const String& other)
{
if (this->str != nullptr)
{
delete[] str;
str = nullptr;
}
lenght = other.lenght;
this->str = new char[lenght + 1];
for (int i = 0; i < lenght; i++)
{
this->str[i] = other.str[i];
}
this->str[other.lenght] = '\0';
return *this;
}
String String::operator+(const String& other)
{
String NewStr;
NewStr.lenght = this->lenght + other.lenght;
NewStr.str = new char[NewStr.lenght + 1];
int i = 0;
for (;i < this->lenght; i++)
{
NewStr.str[i] = this->str[i];
}
for (int j = 0; j < other.lenght; j++, i++)
{
NewStr.str[i] = other.str[j];//предупреждение в этой строке
}
NewStr.str[NewStr.lenght] = '\0';
return NewStr;
}
int main()
{
String a("Hello");
String b("lello");
String c;
c = a + b;
c.print();
}
更换时
NewStr.lenght = this->lenght + other.lenght;
NewStr.str = new char[NewStr.lenght + 1];
在
NewStr.lenght = this->lenght + other.lenght;
NewStr.str = new char[this->lenght + other.lenght + 1];
警告消失