Не удается вернуть результат сложения строк
Результат метода успешно записывается в переменную, если верить отладчику, но при возвращении переменной данные теряются и возвращается случайный набор символов.
MyString& operator + (const MyString& other)
{
MyString result;
result.str = new char[strlen(this->str) + strlen(other.str) + 1];
for (int i = 0; i < strlen(str); i++)
result.str[i] = this->str[i];
for (int i = 0; i < strlen(other.str); i++)
result.str[i+strlen(this->str)] = other.str[i];
result.str[strlen(str) + strlen(other.str)] = '\0';
return result;
Уточняю код класса:
class MyString
{
public:
MyString()
{
str = nullptr;
size = 0;
}
MyString(const char* str)
{
size_t size = strlen(str);
this->str = new char[size+1];
for (int i = 0; i < size; i++)
{
this->str[i] = str[i];
}
this->str[size] = '\0';
}
~MyString()
{
delete[] this->str;
}
void Print()
{
cout << str;
}
MyString(const MyString& other)
{
size_t size = strlen(other.str);
this->str = new char[size + 1];
for (int i = 0; i < size; i++)
{
this->str[i] = other.str[i];
}
this->str[size] = '\0';
};
MyString& operator = (const MyString& other)
{
if (this->str != nullptr)
delete[] str;
size_t size = strlen(other.str);
this->str = new char[size + 1];
for (int i = 0; i < size; i++)
{
this->str[i] = other.str[i];
}
this->str[size] = '\0';
return *this;
};
MyString operator + (const MyString& other)
{
MyString result;
result.str = new char[strlen(this->str) + strlen(other.str) + 1];
for (int i = 0; i < strlen(str); i++)
result.str[i] = this->str[i];
for (int i = 0; i < strlen(other.str); i++)
result.str[i+strlen(this->str)] = other.str[i];
result.str[strlen(str) + strlen(other.str)] = '\0';
return result;
}
private:
char* str;
size_t size{};
};