
Примеры отчетов / ООП. Лаб. 2
.docx
ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ "САНКТ-ПЕТЕРБУРГСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ ТЕЛЕКОММУНИКАЦИЙ ИМ. ПРОФ. М. А. БОНЧ-БРУЕВИЧА"
Факультет инфокоммуникационных сетей и систем
Кафедра программной инженерии и вычислительной техники
ЛАБОРАТОРНАЯ РАБОТА №2
«ОТНОШЕНИЕ ВКЛЮЧЕНИЯ»
по дисциплине «Объектно-ориентированное программирование»
Выполнил:
студент 2 курса
дневного отделения
группы ИКПИ-81
Коваленко Л. А.
Санкт-Петербург 2019
А. Постановка задачи
Разработать определения двух классов COne и CTwo, которые связаны отношением включения. Для всех классов требуется написать:
-
Три вида конструкторов (по умолчанию / с параметрами, конструктор копирования и конструктор перемещения),
-
Деструктор,
-
Перегруженный оператор присваивания,
-
Методы доступа и метод print(), распечатывающий значения полей объекта.
Написать тестовую программу для проверки работоспособности разработанных классов.
Б. Таблицы атрибутов классов
Таблица атрибутов класса COne
N |
Назначение |
Идентификатор |
Секция |
1 |
Число типа long |
L (long) |
protected |
2 |
Строка типа std::string |
S (std::string) |
protected |
Таблица атрибутов класса CTwo
N |
Назначение |
Идентификатор |
Секция |
1 |
Указатель на объект типа COne |
P (COne *) |
protected |
2 |
Строка типа std::string |
S (std::string) |
protected |
В. Код программы
Код программы с классами COne и CTwo |
#include <iostream> #include <string> #include <stdexcept> using std::cin; using std::cout; using std::endl; using std::string; class COne { protected: long L; string S; public: // Конструктор explicit COne(string input = "", long L = 0) : S(std::move(input)), L(L) {} // Конструктор копирования COne(const COne &arg) { L = arg.L; S = arg.S; } // Оператор копирования COne &operator=(const COne &arg) { COne temp(arg); std::swap(L, temp.L); std::swap(S, temp.S); return *this; } // Конструктор перемещения COne(COne &&arg) noexcept { L = arg.L, arg.L = 0; S = std::move(arg.S); } // Оператор перемещения COne &operator=(COne &&arg) noexcept { if (this != &arg) { std::swap(L, arg.L); std::swap(S, arg.S); arg.L = 0, arg.S.clear(); } return *this; } // Деструктор virtual ~COne() { S.clear(); }; // Получение доступа к значению L const long &getValue() const { return L; } // Получение доступа к строке S const string &getString() const { return S; } // Длина строки size_t len() const { return S.size(); } // Печать полей класса virtual void print() const { cout << "COne {" << L << ", \"" << S << "\"}"; } friend class CTwo; }; class CTwo { protected: string S; COne *P; // ОТНОШЕНИЕ ВКЛЮЧЕНИЯ public: // Конструктор explicit CTwo(string s = "", string ps = "", int number = 0) : S(std::move(s)) { P = new COne(std::move(ps), number); } // Конструктор копирования CTwo(const CTwo &arg) { P = new COne(*arg.P); S = arg.S; } // Оператор копирования CTwo &operator=(const CTwo &arg) { CTwo temp(arg); std::swap(P, temp.P); std::swap(S, temp.S); return *this; } // Конструктор перемещения CTwo(CTwo &&arg) noexcept { P = arg.P, arg.P = nullptr; S = std::move(arg.S); } // Оператор перемещения CTwo &operator=(CTwo &&arg) noexcept { if (this != &arg) { std::swap(P, arg.P); std::swap(S, arg.S); delete arg.P, arg.P = nullptr; arg.S.clear(); } return *this; } // Деструктор virtual ~CTwo() { delete P; S.clear(); } // Получение доступа к объекту типа COne const COne *getCOne() const { return P; } // Получение доступа к строке S const string &getString() const { return S; } // Длина строки size_t len() const { return S.size(); } // Печать полей класса virtual void print() const { cout << "CTwo [ "; if (P) { cout << '\"' << S << "\", "; P->print(); } else { cout << "undefined"; } cout << " ]"; } }; |
Г. Вывод программы
Вывод программы с классами COne и CTwo |
int main() { const int N = 5; // Создание объекта CTwo tA("Text string", "Text string 2", N); // Вызов метода print() для печати информации об объекте cout << "tA: ", tA.print(), cout << endl; // Вывод длин строк, строк и значения cout << "Lengths tA: " << tA.len() << ' ' << tA.getCOne()->len() << endl; cout << "Strings tA: " << tA.getString() << ' ' << tA.getCOne()->getString() << endl; cout << "Value tA: " << tA.getCOne()->getValue() << endl; // Копирование конструктором cout << "======================" << endl; cout << "== Copy constructor ==" << endl; CTwo tC(tA); cout << "tA: ", tA.print(), cout << endl; cout << "tC: ", tC.print(), cout << endl; // Копирование присваиванием cout << "=====================" << endl; cout << "== Copy assignment ==" << endl; tC = tA; cout << "tA: ", tA.print(), cout << endl; cout << "tC: ", tC.print(), cout << endl; // Перемещение конструктором cout << "======================" << endl; cout << "== Move constructor ==" << endl; CTwo tD(std::move(tA)); cout << "tA: ", tA.print(), cout << endl; cout << "tD: ", tD.print(), cout << endl; // Перемещение присваиванием cout << "=====================" << endl; cout << "== Move assignment ==" << endl; tD = std::move(tC); cout << "tC: ", tC.print(), cout << endl; cout << "tD: ", tD.print(), cout << endl; } |
tA: CTwo [ "Text string", COne {5, "Text string 2"} ] Lengths tA: 11 13 Strings tA: Text string Text string 2 Value tA: 5 ====================== == Copy constructor == tA: CTwo [ "Text string", COne {5, "Text string 2"} ] tC: CTwo [ "Text string", COne {5, "Text string 2"} ] ===================== == Copy assignment == tA: CTwo [ "Text string", COne {5, "Text string 2"} ] tC: CTwo [ "Text string", COne {5, "Text string 2"} ] ====================== == Move constructor == tA: CTwo [ undefined ] tD: CTwo [ "Text string", COne {5, "Text string 2"} ] ===================== == Move assignment == tC: CTwo [ undefined ] tD: CTwo [ "Text string", COne {5, "Text string 2"} ] |