Загрузка данных


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;


class MyStr {
    int length{0};               // length of the string
    char* buff{nullptr};              // pointer to strorage
public:   

    MyStr() : length(0), buff(nullptr)
    {
        cout << "  MyStr default constr.\n";
    }

    MyStr(const char* init_val)  //MyStr s("hello");       
    {
        if (init_val != nullptr && *init_val != '\0')
        {
            length = strlen(init_val);
            buff = new char[length + 1];
            strcpy(buff, init_val);
        }
        cout << "  MyStr( char * ) constr.\n";
    }

    MyStr(const MyStr& other) :
        length(other.length),
        buff(new char[length + 1])
    {
        cout << "  MyStr copy const.\n";
        strcpy(buff, other.buff);
    }

    ~MyStr()
    {
        cout << "  MyStr destr.\n";
        delete[] buff;
    }

    int size() { return length; }

    MyStr& operator= (const MyStr& other)
    {
        cout << "  MyStr::operator=\n";
        if (this != &other) {         
            delete[] buff;            
            buff = nullptr; 
            length = other.length;       
            if(length == 0)
                buff = nullptr; 
            else
            {
                buff = new char[length + 1];
                strcpy(buff, other.buff);
            }
        }
        return *this;                
    }                                


    friend MyStr operator+(const MyStr& s1, const MyStr& s2);
    friend ostream& operator<< (ostream&, const MyStr&);

    char& operator[] (int index)
    {
        if (index < 0 || index > length) {
            cerr << "Invalid index in MyStr::operator[]. Aborting...\n";
            exit(-1);  
        }
        return buff[index];
    }
};
MyStr operator+(const MyStr& s1, const MyStr& s2)
{
    MyStr res;
    if (s1.length == 0 && s2.length == 0)
        return res;

    res.length = s1.length + s2.length;
    res.buff = new char[res.length+1];
    if(s1.length != 0)
        strcpy(res.buff, s1.buff);
    if(s2.length != 0)
        strcat(res.buff, s2.buff);
       
    return res;
}
ostream& operator<< (ostream& os, const MyStr& s)  {
    for (int i = 0; i < s.length; i++)  os.put(s.buff[i]);
    return os;         
}


int main() {
    MyStr a = "Hello ";
    MyStr b = "World!";
    MyStr c = a;
    c = a + b;
    cout << c << endl;
    
    return 0; 
}