Untitled

 avatar
unknown
plain_text
17 days ago
1.5 kB
4
Indexable
#include <iostream>
#include <cstring>

class String {
private:
    char* data;

public:
    // 1. Обычный конструктор
    String(const char* s = "") {
        data = new char[strlen(s) + 1];
        strcpy(data, s);
    }

    // 2. Деструктор (освобождаем память)
    ~String() {
        delete[] data;
    }

    // 3. Конструктор копирования (создаем новую память для копии)
    String(const String& other) {
        data = new char[strlen(other.data) + 1];
        strcpy(data, other.data);
    }

    // 4. Оператор присваивания (чистим старое, выделяем новое)
    String& operator=(const String& other) {
        if (this == &other) return *this; // Защита от a = a
        delete[] data;                   // Удаляем свое старое
        data = new char[strlen(other.data) + 1];
        strcpy(data, other.data);
        return *this;
    }

    void print() { std::cout << data << std::endl; }
};

int main() {
    String s1("Hello");
    String s2 = s1;      // Сработал конструктор копирования
    String s3;
    s3 = s2;             // Сработал оператор присваивания

    s1.print();
    s2.print();
    s3.print();
    return 0;
} // Тут деструкторы безопасно удалят три разных массива
Editor is loading...
Leave a Comment