TGViewer
Алгоритмы - Собеседования, Олимпиады, ШАД Алгоритмы - Собеседования, Олимпиады, ШАД @algoses · 12.1K subscribers
Post #375 6.9K

Forwarded from Art of Code

Задача с собеса в Ягуар

Задача: Напишите конструктор копирования для 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
  • 🥱 14
  • ❤ 3
  • 🔥 2
  • 😁 1
  • 🤣 1
More from @algoses
  1. Sep 26, 2026Ты поступишь в ШАД Старт набора на наши ШАДовские курсы: без воды и лишней теории, 3 месяц…
  2. Sep 25, 2026Как залететь в хфт и стать миллионером, залутать сочную зумершку? Обсудим в новом ролике.…
  3. Sep 23, 2026Задача с собеседования в Zoho Даны две строки s и t. Определите, являются ли они изоморфны…
  4. Sep 19, 2026Полный цикл отбора в Spectral на SWE (HFT) Недавно рассказывали про отбор в Fast Forward н…
  5. Sep 18, 2026❗️ Яндекс открыл Intern Week Offer на стажировку, где всего за неделю ты можешь получить о…
  6. Sep 18, 2026Задача с собеседования в Zeta Зима близко! Во время соревнования ваша первая задача - спро…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →