Задача: Напишите конструктор копирования для A. Для тех кто неуверенно (с подсказкой) справился с предыдущей задачей: напишите
operator= для класса A. чтобы проверить, что всё поняли.class Cloneable {
public:
virtual Cloneable* clone() const = 0; // Возвращает копию себя
virtual ~Cloneable() {}
};
class A {
public:
A(/* Какой должна быть сигнатура конструктора копирования? */);
~A();
// Добавить оператор присваивания
private:
Cloneable* b;
Cloneable* c;
std::string* s;
};
A::~A() {
delete b;
delete c;
delete s;
}Решение:
Конструктор копирования: A::A(const A& other)
: b(other.b ? other.b->clone() : nullptr),
c(other.c ? other.c->clone() : nullptr),
s(other.s ? new std::string(*other.s) : nullptr) {}
Оператор присваивания: A& A::operator=(const A& other) {
if (this != &other) { // Проверка на самоприсваивание
// Удаляем старые данные
delete b;
delete c;
delete s;
// Копируем новые данные
b = other.b ? other.b->clone() : nullptr;
c = other.c ? other.c->clone() : nullptr;
s = other.s ? new std::string(*other.s) : nullptr;
}
return *this;
}
Полный код: class A {
public:
A() : b(nullptr), c(nullptr), s(nullptr) {} // Конструктор по умолчанию
A(const A& other); // Конструктор копирования
A& operator=(const A& other); // Оператор присваивания
~A();
private:
Cloneable* b;
Cloneable* c;
std::string* s;
};
// Реализации
A::A(const A& other)
: b(other.b ? other.b->clone() : nullptr),
c(other.c ? other.c->clone() : nullptr),
s(other.s ? new std::string(*other.s) : nullptr) {}
A& A::operator=(const A& other) {
if (this != &other) {
delete b;
delete c;
delete s;
b = other.b ? other.b->clone() : nullptr;
c = other.c ? other.c->clone() : nullptr;
s = other.s ? new std::string(*other.s) : nullptr;
}
return *this;
}
A::~A() {
delete b;
delete c;
delete s;
}
@codeof_art