diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..9faae8a --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,36 @@ +{ + "configurations": [ + + { + "name": "C/C++: g++ сборка и отладка активного файла", + "type": "cppdbg", + "request": "launch", + "program": "${fileDirname}/${fileBasenameNoExtension}", + "args": [], + "stopAtEntry": false, + "cwd": "${fileDirname}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "setupCommands": [ + { + "description": "Включить автоматическое форматирование для gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + }, + { + "description": "Задать для варианта приложения дизассемблирования значение Intel", + "text": "-gdb-set disassembly-flavor intel", + "ignoreFailures": true + } + ], + "existing": false, + "preLaunchTask": "C/C++: g++ сборка активного файла", + "detail": "ЗадачаПредварительногоЗапуска: C/C++: g++ сборка активного файла", + "taskDetail": "Задача создана отладчиком.", + "taskStatus": "Recently Used Task", + "isDefault": true, + "miDebuggerPath": "/usr/bin/gdb" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..956e9cc --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,49 @@ +{ + "files.associations": { + "array": "cpp", + "atomic": "cpp", + "bit": "cpp", + "*.tcc": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "unordered_map": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "string": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "fstream": "cpp", + "initializer_list": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "ostream": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "typeinfo": "cpp", + "ctime": "cpp" + } +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..9b058b6 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,48 @@ +{ + "tasks": [ + { + "type": "cppbuild", + "label": "C/C++: g++ сборка активного файла", + "command": "/usr/bin/g++", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}/${fileBasenameNoExtension}" + ], + "options": { + "cwd": "${fileDirname}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": "build", + "detail": "Задача создана отладчиком." + }, + { + "type": "cppbuild", + "label": "C/C++: g++-9 сборка активного файла", + "command": "/usr/bin/g++-9", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}/${fileBasenameNoExtension}" + ], + "options": { + "cwd": "${fileDirname}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "detail": "Задача создана отладчиком." + } + ], + "version": "2.0.0" +} \ No newline at end of file diff --git a/dz 2.1 b/Chapter 2/dz 2.1 similarity index 100% rename from dz 2.1 rename to Chapter 2/dz 2.1 diff --git a/Chapter 3/3.1 b/Chapter 3/3.1 deleted file mode 100644 index 65fdbeb..0000000 --- a/Chapter 3/3.1 +++ /dev/null @@ -1,53 +0,0 @@ -#include -#include -#include - -class Book { -protected: - std::string title; -public: - Book(std::string title) : title(title) {} - virtual void display() const { - std::cout << "Book: " << title << std::endl; - } -}; - -class Textbook : public Book { -private: - std::string subject; -public: - Textbook(std::string title, std::string subject) : Book(title), subject(subject) {} - void display() const override { - std::cout << "Textbook: " << title << " on " << subject << std::endl; - } -}; - -class Library { -private: - std::vector books; -public: - void addBook(Book* book) { - books.push_back(book); - } - - void displayBooks() const { - for (const auto& book : books) { - book->display(); - } - } - - ~Library() { - for (auto& book : books) { - delete book; - } - } -}; - -int main() { - Library library; - library.addBook(new Book("1984")); - library.addBook(new Textbook("Physics", "Science")); - - library.displayBooks(); - return 0; -} diff --git a/Chapter 3/3.2 b/Chapter 3/3.2 deleted file mode 100644 index ea1448e..0000000 --- a/Chapter 3/3.2 +++ /dev/null @@ -1,53 +0,0 @@ -#include -#include -#include - -class Student { -protected: - std::string name; -public: - Student(std::string name) : name(name) {} - virtual void display() const { - std::cout << "Student: " << name << std::endl; - } -}; - -class InternationalStudent : public Student { -private: - std::string country; -public: - InternationalStudent(std::string name, std::string country) : Student(name), country(country) {} - void display() const override { - std::cout << "International Student: " << name << " from " << country << std::endl; - } -}; - -class Course { -private: - std::vector students; -public: - void addStudent(Student* student) { - students.push_back(student); - } - - void displayStudents() const { - for (const auto& student : students) { - student->display(); - } - } - - ~Course() { - for (auto& student : students) { - delete student; - } - } -}; - -int main() { - Course course; - course.addStudent(new Student("John")); - course.addStudent(new InternationalStudent("Alice", "Canada")); - - course.displayStudents(); - return 0; -} diff --git a/Chapter 3/3.3 b/Chapter 3/3.3 deleted file mode 100644 index 26708ea..0000000 --- a/Chapter 3/3.3 +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include - -class Student { -private: - std::string name; -public: - Student(std::string name) : name(name) {} - std::string getName() const { - return name; - } -}; - -class Teacher { -private: - std::string name; -public: - Teacher(std::string name) : name(name) {} - void gradeStudent(const Student& student) { - std::cout << "Teacher " << name << " is grading student " << student.getName() << "." << std::endl; - } -}; - -int main() { - Student student("John"); - Teacher teacher("Dr. Smith"); - - teacher.gradeStudent(student); - return 0; -} diff --git a/Chapter 3/3.4 b/Chapter 3/3.4 deleted file mode 100644 index a9b5958..0000000 --- a/Chapter 3/3.4 +++ /dev/null @@ -1,25 +0,0 @@ -#include -#include - -class EmailService { -public: - void sendEmail(const std::string& recipient, const std::string& message) const { - std::cout << "Sending email to " << recipient << ": " << message << std::endl; - } -}; - -class NotificationService { -private: - EmailService emailService; -public: - void notifyUser(const std::string& recipient, const std::string& message) { - emailService.sendEmail(recipient, message); - } -}; - -int main() { - NotificationService notificationService; - notificationService.notifyUser("john@example.com", "Your package has been shipped!"); - - return 0; -} diff --git a/Chapter 3/3.6 b/Chapter 3/3.6 deleted file mode 100644 index 70a58f4..0000000 --- a/Chapter 3/3.6 +++ /dev/null @@ -1,40 +0,0 @@ -#include - -class Animal { -public: - virtual void sound() const { - std::cout << "Some generic animal sound" << std::endl; - } - - virtual ~Animal() = default; -}; - -class Dog : public Animal { -public: - void sound() const override { - std::cout << "Woof!" << std::endl; - } -}; - -class Cat : public Animal { -public: - void sound() const override { - std::cout << "Meow!" << std::endl; - } -}; - -int main() { - Animal* animals[2]; - animals[0] = new Dog(); - animals[1] = new Cat(); - - for (int i = 0; i < 2; ++i) { - animals[i]->sound(); - } - - for (int i = 0; i < 2; ++i) { - delete animals[i]; - } - - return 0; -} diff --git a/Chapter 3/3_1 b/Chapter 3/3_1 new file mode 100755 index 0000000..127a287 Binary files /dev/null and b/Chapter 3/3_1 differ diff --git a/Chapter 3/3_1.cpp b/Chapter 3/3_1.cpp new file mode 100644 index 0000000..5b8cebb --- /dev/null +++ b/Chapter 3/3_1.cpp @@ -0,0 +1,67 @@ +#include +#include +#include + +// Класс Book +class Book { +public: + std::string title; + std::string author; + + Book(const std::string &title, const std::string &author) + : title(title), author(author) {} + + virtual void displayInfo() const { + std::cout << "Book: " << title << " by " << author << std::endl; + } +}; + +// Класс Textbook, наследующий от Book +class Textbook : public Book { +public: + std::string subject; + + Textbook(const std::string &title, const std::string &author, const std::string &subject) + : Book(title, author), subject(subject) {} + + void displayInfo() const override { + std::cout << "Textbook: " << title << " by " << author << ", Subject: " << subject << std::endl; + } +}; + +// Класс Library +class Library { +private: + std::vector books; + +public: + void addBook(Book* book) { + books.push_back(book); + } + + void displayBooks() const { + for (const auto &book : books) { + book->displayInfo(); + } + } + + ~Library() { + for (auto &book : books) { + delete book; + } + } +}; + +int main() { + Library library; + + Book* book1 = new Book("1984", "George Orwell"); + Textbook* textbook1 = new Textbook("Calculus", "James Stewart", "Mathematics"); + + library.addBook(book1); + library.addBook(textbook1); + + library.displayBooks(); + + return 0; +} diff --git a/Chapter 3/3_2 b/Chapter 3/3_2 new file mode 100755 index 0000000..7c3a94c Binary files /dev/null and b/Chapter 3/3_2 differ diff --git a/Chapter 3/3_2.cpp b/Chapter 3/3_2.cpp new file mode 100644 index 0000000..2486fb5 --- /dev/null +++ b/Chapter 3/3_2.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +// Класс Student +class Student { +public: + std::string name; + + Student(const std::string &name) : name(name) {} + + virtual void displayInfo() const { + std::cout << "Student: " << name << std::endl; + } +}; + +// Класс InternationalStudent, наследующий от Student +class InternationalStudent : public Student { +public: + std::string country; + + InternationalStudent(const std::string &name, const std::string &country) + : Student(name), country(country) {} + + void displayInfo() const override { + std::cout << "International Student: " << name << ", Country: " << country << std::endl; + } +}; + +// Класс Course +class Course { +private: + std::vector students; + +public: + void addStudent(Student* student) { + students.push_back(student); + } + + void displayStudents() const { + for (const auto &student : students) { + student->displayInfo(); + } + } + + ~Course() { + for (auto &student : students) { + delete student; + } + } +}; + +int main() { + Course course; + + Student* student1 = new Student("Alice"); + InternationalStudent* student2 = new InternationalStudent("Bob", "Canada"); + + course.addStudent(student1); + course.addStudent(student2); + + course.displayStudents(); + + return 0; +} diff --git a/Chapter 3/3_3 b/Chapter 3/3_3 new file mode 100755 index 0000000..d8d04ee Binary files /dev/null and b/Chapter 3/3_3 differ diff --git a/Chapter 3/3_3.cpp b/Chapter 3/3_3.cpp new file mode 100644 index 0000000..857f6b7 --- /dev/null +++ b/Chapter 3/3_3.cpp @@ -0,0 +1,68 @@ +#include +#include + +// Класс Student +class Student { +public: + std::string name; + int grade; + + Student(const std::string &name) : name(name), grade(0) {} + + virtual void displayInfo() const { + std::cout << "Student: " << name << ", Grade: " << grade << std::endl; + } + + void setGrade(int grade) { + this->grade = grade; + } +}; + +// Класс InternationalStudent, наследующий от Student +class InternationalStudent : public Student { +public: + std::string country; + + InternationalStudent(const std::string &name, const std::string &country) + : Student(name), country(country) {} + + void displayInfo() const override { + std::cout << "International Student: " << name << ", Country: " << country << ", Grade: " << grade << std::endl; + } +}; + +// Класс Teacher +class Teacher { +private: + std::string name; + Student &student; + +public: + Teacher(const std::string &name, Student &student) : name(name), student(student) {} + + void evaluateStudent(int grade) { + student.setGrade(grade); + std::cout << name << " evaluated " << student.name << " with a grade of " << grade << std::endl; + } + + void displayInfo() const { + std::cout << "Teacher: " << name << std::endl; + student.displayInfo(); + } +}; + +int main() { + Student student1("Alice"); + InternationalStudent student2("Bob", "Canada"); + + Teacher teacher1("Mr. Smith", student1); + Teacher teacher2("Ms. Johnson", student2); + + teacher1.evaluateStudent(85); + teacher2.evaluateStudent(90); + + teacher1.displayInfo(); + teacher2.displayInfo(); + + return 0; +} diff --git a/Chapter 3/3_4 b/Chapter 3/3_4 new file mode 100755 index 0000000..c3779d3 Binary files /dev/null and b/Chapter 3/3_4 differ diff --git a/Chapter 3/3.5 b/Chapter 3/3_4.cpp similarity index 54% rename from Chapter 3/3.5 rename to Chapter 3/3_4.cpp index a9b5958..224f353 100644 --- a/Chapter 3/3.5 +++ b/Chapter 3/3_4.cpp @@ -1,25 +1,28 @@ #include #include +// Класс EmailService class EmailService { public: - void sendEmail(const std::string& recipient, const std::string& message) const { + void sendEmail(const std::string &recipient, const std::string &message) { std::cout << "Sending email to " << recipient << ": " << message << std::endl; } }; +// Класс NotificationService class NotificationService { private: EmailService emailService; + public: - void notifyUser(const std::string& recipient, const std::string& message) { + void notifyUser(const std::string &recipient, const std::string &message) { emailService.sendEmail(recipient, message); } }; int main() { NotificationService notificationService; - notificationService.notifyUser("john@example.com", "Your package has been shipped!"); + notificationService.notifyUser("user@example.com", "Hello, this is a notification!"); return 0; } diff --git a/Chapter 3/3_5.cpp b/Chapter 3/3_5.cpp new file mode 100644 index 0000000..03b32bf --- /dev/null +++ b/Chapter 3/3_5.cpp @@ -0,0 +1,50 @@ +#include +#include +#include + +// Базовый класс Animal +class Animal { +public: + virtual void sound() const { + std::cout << "Some generic animal sound" << std::endl; + } + + virtual ~Animal() {} // Виртуальный деструктор для корректного удаления производных объектов +}; + +// Производный класс Dog +class Dog : public Animal { +public: + void sound() const override { + std::cout << "Woof!" << std::endl; + } +}; + +// Производный класс Cat +class Cat : public Animal { +public: + void sound() const override { + std::cout << "Meow!" << std::endl; + } +}; + +int main() { + // Создаем массив указателей на Animal + std::vector animals; + + // Заполняем массив объектами Dog и Cat + animals.push_back(new Dog()); + animals.push_back(new Cat()); + + // Выводим звуки, используя полиморфизм + for (const auto &animal : animals) { + animal->sound(); + } + + // Очистка памяти + for (auto &animal : animals) { + delete animal; + } + + return 0; +} diff --git a/Chapter 4/4_1 b/Chapter 4/4_1 new file mode 100755 index 0000000..0339905 Binary files /dev/null and b/Chapter 4/4_1 differ diff --git a/Chapter 4/4.1 b/Chapter 4/4_1.cpp similarity index 97% rename from Chapter 4/4.1 rename to Chapter 4/4_1.cpp index 07436fc..64ab618 100644 --- a/Chapter 4/4.1 +++ b/Chapter 4/4_1.cpp @@ -41,7 +41,7 @@ class Date { }; int main() { - Date date(25, 2, 2024); + Date date(31, 12, 2024); Date newDate = date + 10; newDate.display(); return 0; diff --git a/Chapter 4/4_2 b/Chapter 4/4_2 new file mode 100755 index 0000000..71fb925 Binary files /dev/null and b/Chapter 4/4_2 differ diff --git a/Chapter 4/4.2 b/Chapter 4/4_2.cpp similarity index 100% rename from Chapter 4/4.2 rename to Chapter 4/4_2.cpp diff --git a/Chapter 4/4_3 b/Chapter 4/4_3 new file mode 100755 index 0000000..d71bd78 Binary files /dev/null and b/Chapter 4/4_3 differ diff --git a/Chapter 4/4.3 b/Chapter 4/4_3.cpp similarity index 100% rename from Chapter 4/4.3 rename to Chapter 4/4_3.cpp diff --git a/Chapter 4/4_4 b/Chapter 4/4_4 new file mode 100755 index 0000000..a74dd2a Binary files /dev/null and b/Chapter 4/4_4 differ diff --git a/Chapter 4/4.4 b/Chapter 4/4_4.cpp similarity index 100% rename from Chapter 4/4.4 rename to Chapter 4/4_4.cpp diff --git a/Chapter 5/5_1 b/Chapter 5/5_1 new file mode 100755 index 0000000..cac3b30 Binary files /dev/null and b/Chapter 5/5_1 differ diff --git a/5.cpp b/Chapter 5/5_1.cpp similarity index 100% rename from 5.cpp rename to Chapter 5/5_1.cpp diff --git a/Chapter 5/5_2 b/Chapter 5/5_2 new file mode 100755 index 0000000..d884d75 Binary files /dev/null and b/Chapter 5/5_2 differ diff --git a/5_2.cpp b/Chapter 5/5_2.cpp similarity index 100% rename from 5_2.cpp rename to Chapter 5/5_2.cpp diff --git a/Chapter 5/5_3 b/Chapter 5/5_3 new file mode 100755 index 0000000..261eb76 Binary files /dev/null and b/Chapter 5/5_3 differ diff --git a/5_3.cpp b/Chapter 5/5_3.cpp similarity index 100% rename from 5_3.cpp rename to Chapter 5/5_3.cpp diff --git a/Chapter 5/5_4 b/Chapter 5/5_4 new file mode 100755 index 0000000..4bc4c39 Binary files /dev/null and b/Chapter 5/5_4 differ diff --git a/5_4.cpp b/Chapter 5/5_4.cpp similarity index 82% rename from 5_4.cpp rename to Chapter 5/5_4.cpp index d70b5a4..c007377 100644 --- a/5_4.cpp +++ b/Chapter 5/5_4.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include template class Matrix { @@ -17,7 +19,7 @@ class Matrix { void input() { for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < cols; ++j) { - std::cin >> data[i][j]; + data[i][j] = std::rand() % 11; } } } @@ -82,22 +84,12 @@ class Matrix { }; int main() { - int a, a2, b, b2; - + srand(static_cast(time(0))); - std::cout << "Введите размеры матрицы A:" << std::endl; - std::cin >> a >> a2; + Matrix A(2, 3); + Matrix B(2, 3); - std::cout << "Введите размеры матрицы B:" << std::endl; - std::cin >> b >> b2; - - Matrix A(a, a2); - Matrix B(b, b2); - - std::cout << "Введите элементы матрицы A:" << std::endl; A.input(); - - std::cout << "Введите элементы матрицы B:" << std::endl; B.input(); std::cout << "Матрица A:" << std::endl; @@ -106,7 +98,7 @@ int main() { std::cout << "Матрица B:" << std::endl; B.output(); - Matrix C = A + B; + Matrix C = A + B; std::cout << "Матрица A + B:" << std::endl; C.output(); @@ -114,14 +106,13 @@ int main() { std::cout << "Матрица A - B:" << std::endl; C.output(); - Matrix D(3, 2); - std::cout << "Введите элементы матрицы D:" << std::endl; + Matrix D(3, 2); D.input(); std::cout << "Матрица D:" << std::endl; D.output(); - Matrix E = A * D; + Matrix E = A * D; std::cout << "Матрица A * D:" << std::endl; E.output(); diff --git a/Chapter 5/5_5 b/Chapter 5/5_5 new file mode 100755 index 0000000..27312e0 Binary files /dev/null and b/Chapter 5/5_5 differ diff --git a/5_5.cpp b/Chapter 5/5_5.cpp similarity index 100% rename from 5_5.cpp rename to Chapter 5/5_5.cpp diff --git a/Chapter 6/1.cpp b/Chapter 6/1.cpp new file mode 100644 index 0000000..c33b3d7 --- /dev/null +++ b/Chapter 6/1.cpp @@ -0,0 +1,37 @@ +#include + +class Transport { +public: + virtual void move() const { + std::cout << "Transport is moving" << std::endl; + } +}; + +class LandTransport : virtual public Transport { +public: + void drive() const { + std::cout << "LandTransport is driving" << std::endl; + } +}; + +class WaterTransport : virtual public Transport { +public: + void sail() const { + std::cout << "WaterTransport is sailing" << std::endl; + } +}; + +class AmphibiousVehicle : public LandTransport, public WaterTransport { +public: + void move() const override { + std::cout << "AmphibiousVehicle is moving" << std::endl; + } +}; + +int main() { + AmphibiousVehicle av; + av.move(); + av.drive(); + av.sail(); + return 0; +} diff --git a/Chapter 6/2.cpp b/Chapter 6/2.cpp new file mode 100644 index 0000000..6051851 --- /dev/null +++ b/Chapter 6/2.cpp @@ -0,0 +1,37 @@ +#include + +class Animal { +public: + virtual void speak() const { + std::cout << "Animal is speaking" << std::endl; + } +}; + +class Mammal : virtual public Animal { +public: + void walk() const { + std::cout << "Mammal is walking" << std::endl; + } +}; + +class Bird : virtual public Animal { +public: + void fly() const { + std::cout << "Bird is flying" << std::endl; + } +}; + +class Bat : public Mammal, public Bird { +public: + void speak() const override { + std::cout << "Bat is speaking" << std::endl; + } +}; + +int main() { + Bat bat; + bat.speak(); + bat.walk(); + bat.fly(); + return 0; +} diff --git a/Chapter 6/3.cpp b/Chapter 6/3.cpp new file mode 100644 index 0000000..da7f442 --- /dev/null +++ b/Chapter 6/3.cpp @@ -0,0 +1,37 @@ +#include + +class Instrument { +public: + virtual void play() const { + std::cout << "Instrument is playing" << std::endl; + } +}; + +class StringInstrument : virtual public Instrument { +public: + void tune() const { + std::cout << "StringInstrument is tuning" << std::endl; + } +}; + +class PercussionInstrument : virtual public Instrument { +public: + void hit() const { + std::cout << "PercussionInstrument is hitting" << std::endl; + } +}; + +class DrumGuitar : public StringInstrument, public PercussionInstrument { +public: + void play() const override { + std::cout << "DrumGuitar is playing" << std::endl; + } +}; + +int main() { + DrumGuitar dg; + dg.play(); + dg.tune(); + dg.hit(); + return 0; +} diff --git a/Chapter 6/4.cpp b/Chapter 6/4.cpp new file mode 100644 index 0000000..e71b793 --- /dev/null +++ b/Chapter 6/4.cpp @@ -0,0 +1,37 @@ +#include + +class Employee { +public: + virtual void work() const { + std::cout << "Employee is working" << std::endl; + } +}; + +class Manager : virtual public Employee { +public: + void delegate() const { + std::cout << "Manager is delegating" << std::endl; + } +}; + +class Developer : virtual public Employee { +public: + void code() const { + std::cout << "Developer is coding" << std::endl; + } +}; + +class TechManager : public Manager, public Developer { +public: + void work() const override { + std::cout << "TechManager is working" << std::endl; + } +}; + +int main() { + TechManager tm; + tm.work(); + tm.delegate(); + tm.code(); + return 0; +} diff --git a/Chapter 6/5.cpp b/Chapter 6/5.cpp new file mode 100644 index 0000000..d3411bd --- /dev/null +++ b/Chapter 6/5.cpp @@ -0,0 +1,37 @@ +#include + +class Performer { +public: + virtual void perform() const { + std::cout << "Performer is performing" << std::endl; + } +}; + +class SoloArtist : virtual public Performer { +public: + void singSolo() const { + std::cout << "SoloArtist is singing solo" << std::endl; + } +}; + +class Band : virtual public Performer { +public: + void playTogether() const { + std::cout << "Band is playing together" << std::endl; + } +}; + +class SuperBand : public SoloArtist, public Band { +public: + void perform() const override { + std::cout << "SuperBand is performing" << std::endl; + } +}; + +int main() { + SuperBand sb; + sb.perform(); + sb.singSolo(); + sb.playTogether(); + return 0; +} diff --git a/Cp 1/zoo b/Cp 1/zoo new file mode 100755 index 0000000..2df6228 Binary files /dev/null and b/Cp 1/zoo differ diff --git a/Cp 1/zoo.cpp b/Cp 1/zoo.cpp new file mode 100644 index 0000000..8a4ce66 --- /dev/null +++ b/Cp 1/zoo.cpp @@ -0,0 +1,201 @@ +#include +#include +#include +#include // Для rand() и srand() +#include // Для time() + +// Интерфейс для кормления животных +class IFeedable { +public: + virtual void Feed() = 0; + virtual bool IsFed() const = 0; +}; + +// Определение шаблонного класса Animal +template +class Animal : public IFeedable { +protected: + std::string name; + int age; + T weight; + bool isFed; + static int nextId; + int id; + +public: + Animal(const std::string &name, int age, T weight) + : name(name), age(age), weight(weight), isFed(false), id(nextId++) {} + + virtual void MakeSound() const = 0; + virtual void DisplayInfo() const { + if (isFed == true){ + std::cout << "Name: " << name << ", Age: " << age << ", Weight: " << weight << " , Status: is being fed" << " , Index: " << id << std::endl; + }else{ + std::cout << "Name: " << name << ", Age: " << age << ", Weight: " << weight << " , Status: isn't being fed" << " , Index: " << id << std::endl; + } + + } + + virtual void Feed() override { + std::cout << name << " is being fed." << std::endl; + isFed = true; + } + + virtual bool IsFed() const override{ + return isFed; + } + + int GetId() const { + return id; + } + + std::string GetName() const { + return name; + } + +}; +template +int Animal::nextId = 1; + +// Производный класс Mammal +template +class Mammal : public Animal { +public: + Mammal(const std::string &name, int age, T weight ) + : Animal(name, age, weight) {} + + void MakeSound() const override { + if (this->name == "Lion") { + std::cout << this->name << " says: Roar!" << std::endl; + } else if (this->name == "Tiger") { + std::cout << this->name << " says: Growl!" << std::endl; + } else if (this->name == "Elephant") { + std::cout << this->name << " says: Trumpet!" << std::endl; + } else { + std::cout << this->name << " says: Mammal sound!" << std::endl; + } + } + + void DisplayInfo() const override { + std::cout << "Mammal - "; + Animal::DisplayInfo(); + } +}; + +// Производный класс Bird +template +class Bird : public Animal { +public: + Bird(const std::string &name, int age, T weight) + : Animal(name, age, weight) {} + + void MakeSound() const override { + if (this->name == "Parrot") { + std::cout << this->name << " says: Squawk!" << std::endl; + } else if (this->name == "Eagle") { + std::cout << this->name << " says: Screech!" << std::endl; + } else { + std::cout << this->name << " says: Chirp!" << std::endl; + } + } + + void DisplayInfo() const override { + std::cout << "Bird - "; + Animal::DisplayInfo(); + } +}; + +// Класс Zoo +class Zoo { +private: + std::vector*> animals; + +public: + void AddAnimal(Animal* animal) { + animals.push_back(animal); + } + + void DisplayAllAnimals() const { + for (const auto &animal : animals) { + animal->DisplayInfo(); + } + } + + void MakeSounds() const { + for (const auto &animal : animals) { + animal->MakeSound(); + } + } + + void FeedAllAnimals() const { + for (const auto &animal : animals) { + if (!animal->IsFed()){ + animal->Feed(); + }else{ + std::cout << "Animal " << animal->GetName() << " with Id: " << animal->GetId() << " is already fed." << std::endl; + } + } + } + + void FeedConrect(int id) const{ + for (const auto& animal : animals) { + if(animal->GetId() == id){ + if (!animal->IsFed()){ + animal->Feed(); + }else{ + std::cout << "Animal " << animal->GetName() << " with Id: " << id << " is already fed." << std::endl; + } + return; + } + } + std::cout << "Animal with Id: " << id << " not found." << std::endl; + } + + ~Zoo() { + for (auto &animal : animals) { + delete animal; + } + } +}; + +// Функция для генерации случайных животных +Animal* CreateRandomAnimal() { + std::string names[] = {"Lion", "Tiger", "Elephant", "Parrot", "Eagle"}; + int age = rand() % 15 + 1; // Возраст от 1 до 15 + double weight = (rand() % 200 + 50) + static_cast(rand()) / RAND_MAX; // Вес от 50 до 250 + + int type = rand() % 2; // 0 для млекопитающих, 1 для птиц + if (type == 0) { + return new Mammal(names[rand() % 3], age, weight); // Млекопитающие + } else { + return new Bird(names[rand() % 2 + 3], age, weight); // Птицы + } +} + +int main() { + srand(static_cast(time(0))); // Инициализация генератора случайных чисел + Zoo zoo; + + // Генерация 10 случайных животных + for (int i = 0; i < 10; ++i) { + Animal* animal = CreateRandomAnimal(); + zoo.AddAnimal(animal); + } + + std::cout << "Animals in the zoo:" << std::endl; + zoo.DisplayAllAnimals(); + + std::cout << "\nAnimals making sounds:" << std::endl; + zoo.MakeSounds(); + + std::cout << "\nFeeding animals with ID 3:" << std::endl; + zoo.FeedConrect(3); + + std::cout << "\nFeeding animals:" << std::endl; + zoo.FeedAllAnimals(); + + std::cout << "\nAnimals after feeding:" << std::endl; + zoo.DisplayAllAnimals(); + + return 0; +} diff --git a/Cp 1/zoo.md b/Cp 1/zoo.md new file mode 100644 index 0000000..f83911f --- /dev/null +++ b/Cp 1/zoo.md @@ -0,0 +1,242 @@ +Зоопарк +Создайте систему управления зоопарком, которая включает классы для животных и зоопарка. Реализуйте следующие функциональные возможности: + +Классы: +Animal: базовый шаблонный класс для животных, который содержит информацию о животном (имя, возраст, вес). Реализуйте виртуальные методы для издания звуков и отображения информации о животном. +Mammal и Bird: производные классы от Animal, которые представляют млекопитающих и птиц соответственно. Реализуйте специфические звуки для каждого типа животных и переопределите метод для отображения информации. +IFeedable: интерфейс, который определяет метод Feed() для кормления животных. Реализуйте этот интерфейс в классах Mammal и Bird. +Zoo: класс, который управляет списком животных. Реализуйте методы для добавления животных, отображения информации о всех животных, издания звуков и кормления всех животных. +Шаблонные классы и полиморфизм: +Используйте шаблонный класс Animal, чтобы поддерживать различные типы данных для веса животных (например, целые числа или числа с плавающей запятой). Реализуйте полиморфизм через виртуальные методы для отображения информации и издания звуков. +Композиция и инкапсуляция: +В классе Zoo используйте композицию для хранения списка животных. Все данные о животных должны быть защищены, а доступ к ним — через публичные методы. +Случайная генерация объектов: +Реализуйте функцию CreateRandomAnimal(), которая будет генерировать случайные объекты классов Mammal и Bird с различными именами, возрастом и весом. Используйте генератор случайных чисел для создания животных. +Интерфейсы и наследование: +Создайте интерфейс IFeedable для реализации кормления животных. Убедитесь, что классы Mammal и Bird реализуют этот интерфейс. +Шаблон +#include +#include +#include +#include // Для rand() и srand() +#include // Для time() + +// Интерфейс для кормления животных +class IFeedable { +}; + +// Определение шаблонного класса Animal +template +class Animal { +}; + +// Производный класс Mammal +template +class Mammal{ +}; + +// Производный класс Bird +template +}; + +// Класс Zoo +class Zoo { +}; + +// Функция для генерации случайных животных +Animal* CreateRandomAnimal() { + std::string names[] = {"Lion", "Tiger", "Elephant", "Parrot", "Eagle"}; + int age = rand() % 15 + 1; // Возраст от 1 до 15 + double weight = (rand() % 200 + 50) + static_cast(rand()) / RAND_MAX; // Вес от 50 до 250 + + int type = rand() % 2; // 0 для млекопитающих, 1 для птиц + if (type == 0) { + return new Mammal(names[rand() % 3], age, weight); // Млекопитающие + } else { + return new Bird(names[rand() % 2 + 3], age, weight); // Птицы + } +} + +int main() { + srand(static_cast(time(0))); // Инициализация генератора случайных чисел + Zoo zoo; + + // Генерация 10 случайных животных + for (int i = 0; i < 10; ++i) { + Animal* animal = CreateRandomAnimal(); + zoo.AddAnimal(animal); + } + + std::cout << "Animals in the zoo:" << std::endl; + zoo.DisplayAllAnimals(); + + std::cout << "\nAnimals making sounds:" << std::endl; + zoo.MakeSounds(); + + std::cout << "\nFeeding animals:" << std::endl; + zoo.FeedAllAnimals(); + + return 0; +} + + +#include +#include +#include +#include // Для rand() и srand() +#include // Для time() + +// Интерфейс для кормления животных +class IFeedable { +public: + virtual void Feed() = 0; +}; + +// Определение шаблонного класса Animal +template +class Animal : public IFeedable { +protected: + std::string name; + int age; + T weight; + bool is_Fed; + int id; + +public: + Animal(const std::string &name, int age, T weight) + : name(name), age(age), weight(weight), is_Fed(false), id(id) {} + + virtual void MakeSound() const = 0; + virtual void DisplayInfo() const { + + }; + virtual void Feed() override { + + }; + virtual bool is_Fed() const override { + + }; + + int GetId() const { + return id; + } +}; + +// Производный класс Mammal +template +class Mammal : public Animal { +public: + Mammal(const std::string &name, int age, T weight ) + : Animal(name, age, weight, id) {} + + void MakeSound() const override { + if (this->name == "Lion") { + std::cout << this->name << " says: Roar!" << std::endl; + } else if (this->name == "Tiger") { + std::cout << this->name << " says: Growl!" << std::endl; + } else if (this->name == "Elephant") { + std::cout << this->name << " says: Trumpet!" << std::endl; + } else { + std::cout << this->name << " says: Mammal sound!" << std::endl; + } + } + + void DisplayInfo() const override { + std::cout << "Mammal - "; + Animal::DisplayInfo(); + } +}; + +// Производный класс Bird +template +class Bird : public Animal { +public: + Bird(const std::string &name, int age, T weight) + : Animal(name, age, weight, id) {} + + void MakeSound() const override { + if (this->name == "Parrot") { + std::cout << this->name << " says: Squawk!" << std::endl; + } else if (this->name == "Eagle") { + std::cout << this->name << " says: Screech!" << std::endl; + } else { + std::cout << this->name << " says: Chirp!" << std::endl; + } + } + + void DisplayInfo() const override { + std::cout << "Bird - "; + Animal::DisplayInfo(); + } +}; + +// Класс Zoo +class Zoo { +private: + std::vector*> animals; + +public: + void AddAnimal(Animal* animal) { + animals.push_back(animal); + } + + void DisplayAllAnimals() const { + for (const auto &animal : animals) { + animal->DisplayInfo(); + } + } + + void MakeSounds() const { + for (const auto &animal : animals) { + animal->MakeSound(); + } + } + + void FeedAllAnimals() const { + for (const auto &animal : animals) { + animal->Feed(); + } + } + + ~Zoo() { + for (auto &animal : animals) { + delete animal; + } + } +}; + +// Функция для генерации случайных животных +Animal* CreateRandomAnimal() { + std::string names[] = {"Lion", "Tiger", "Elephant", "Parrot", "Eagle"}; + int age = rand() % 15 + 1; // Возраст от 1 до 15 + double weight = (rand() % 200 + 50) + static_cast(rand()) / RAND_MAX; // Вес от 50 до 250 + + int type = rand() % 2; // 0 для млекопитающих, 1 для птиц + if (type == 0) { + return new Mammal(names[rand() % 3], age, weight); // Млекопитающие + } else { + return new Bird(names[rand() % 2 + 3], age, weight); // Птицы + } +} + +int main() { + srand(static_cast(time(0))); // Инициализация генератора случайных чисел + Zoo zoo; + + // Генерация 10 случайных животных + for (int i = 0; i < 10; ++i) { + Animal* animal = CreateRandomAnimal(); + zoo.AddAnimal(animal); + } + + std::cout << "Animals in the zoo:" << std::endl; + zoo.DisplayAllAnimals(); + + std::cout << "\nAnimals making sounds:" << std::endl; + zoo.MakeSounds(); + + std::cout << "\nFeeding animals:" << std::endl; + zoo.FeedAllAnimals(); + + return 0; +} diff --git a/README.md b/README.md index 044e415..f98ed5e 100644 --- a/README.md +++ b/README.md @@ -1 +1,12 @@ -# oop +3. Разработайте класс Student (Студент), содержащий поля для имени, возраста и +средней оценки студента. Разработайте класс StudentManager (Менеджер студентов), +который будет управлять массивом студентов, позволяя добавлять, удалять и выводить +информацию о студентах. +4. Разработайте класс Book (Книга), представляющий собой книгу с полями для +названия, автора и года выпуска. Напишите программу, которая создает массив книг, +сортирует его по году выпуска и выводит отсортированный список книг. +5. Разработайте класс BankAccount (Банковский счет), содержащий информацию +о банковском счете (номер счета, баланс). Реализуйте методы для внесения и снятия +средств, а также для метод для перевода средств между счетами. + + diff --git a/lab 1/1.cpp b/lab 1/1.cpp new file mode 100644 index 0000000..b236f66 --- /dev/null +++ b/lab 1/1.cpp @@ -0,0 +1,20 @@ +#include + +class Point +{ +private: + int x, y; +public: + Point(int x = 0, int y = 0) : x(x), y(y) {}; + + void wolk() { + std::cout << "Точка была перемещенна на заданное растояния по x = " << x << ", y = " << y << "." << std::endl; + }; +}; + +int main () { + Point pt(12, 68); + + pt.wolk(); + +} \ No newline at end of file diff --git a/lab 1/2.cpp b/lab 1/2.cpp new file mode 100644 index 0000000..cae5a13 --- /dev/null +++ b/lab 1/2.cpp @@ -0,0 +1,50 @@ +#include + +class Calculator +{ +private: + double x, y; +public: + Calculator(){ + double x = 0.0; + double y = 0.0; + }; + + double plus(double x, double y){ + double sum = x + y; + std::cout << "Сумма этих двух чисел: " << sum << std::endl; + }; + + double minus(double x, double y){ + double inversion_sum = x - y; + std::cout << "Вычитние этих двух чисел: " << inversion_sum << std::endl; + }; + + double division(double x, double y){ + if (x == 0 or y == 0) { + std::cout << "На ноль делить нельзя" << std::endl; + }else{ + double divis = (x / y); + std::cout << "Деление этих двух чисел: " << divis << std::endl; + } + + }; + + double multiplication(double x, double y){ + double multi = x * y; + std::cout << "Произведение этих двух чисел: " << multi << std::endl; + }; +}; + +int main() { + Calculator cal; + + cal.plus(1.23, 4.53); + + cal.minus(4.53, 1.23); + + cal.division(4.5, 0); + cal.division(53.95, 8.3); + + cal.multiplication(6.5, 8.3); +} diff --git a/lab 1/3.cpp b/lab 1/3.cpp new file mode 100644 index 0000000..db29a15 --- /dev/null +++ b/lab 1/3.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + + +class Student +{ +protected: + std::string name; + int age; + double rating; +public: + Student(std::string name, int age, double rating) : + name(name), age(age), rating(rating) {}; + + void DisplayInfo() const { + std::cout << "Имя: " << name << " Возраст: " << age << " Средняя оценка: " << rating << std::endl; + } + + std::string GetName() const { + return name; + } +}; + +class ManagerStudent +{ +private: + std::vector students; +public: + + void AddStudent(const Student& student) { + students.push_back(student); + } + + void RemoveStudent(const std::string &name){ + for (auto it = students.begin(); it != students.end(); ++it) { + if(it->GetName() == name){ + students.erase(it); + std::cout << "Данный студент удалён из списка" << std::endl; + break; + } + } + } + + void StudentInfo() const { + for(const auto& student : students){ + student.DisplayInfo(); + } + } +}; + + +int main() { + ManagerStudent mang; + mang.AddStudent(Student("Alice", 19, 4.5)); + mang.AddStudent(Student("Bob", 23, 3.35)); + mang.AddStudent(Student("Josh", 21, 2.1)); + + mang.StudentInfo(); + + mang.RemoveStudent("Bob"); + + mang.StudentInfo(); + + return 0; +} \ No newline at end of file diff --git a/lab 1/4.cpp b/lab 1/4.cpp new file mode 100644 index 0000000..bf1418d --- /dev/null +++ b/lab 1/4.cpp @@ -0,0 +1,54 @@ +#include +#include +#include + + +class Book +{ +protected: + std::string name; + std::string autor; + int age; +public: + Book(std::string name, std::string autor, int age) : + name(name), autor(autor), age(age) {}; + + void DisplayInfo() const { + std::cout << "Название: " << name << " Год выпуска: " << age << " Автор: " << autor << std::endl; + } + + int GetAge() const { + return age; + } +}; + +void Sort(std::vector& books){ + int n = books.size(); + for( int i = 0; i < n-1; i++){ + for( int j = 0; j < n-1; j++){ + if(books[j].GetAge() > books[j+1].GetAge()){ + std::swap(books[j], books[j + 1]); + } + } + } +} + +void display_books(const std::vector& books) { + for(const auto& book : books){ + book.DisplayInfo(); + } +} + +int main() { + std::vector books = { + Book("Book1", "Auror1", 2000), + Book("Book2", "Auror2", 1990), + Book("Book3", "Auror3", 2010), + Book("Book4", "Auror4", 2010), + Book("Book5", "Auror5", 1975), + Book("Book6", "Auror6", 2110), + }; + + Sort(books); + display_books(books); +} \ No newline at end of file diff --git a/lab 1/5.cpp b/lab 1/5.cpp new file mode 100644 index 0000000..547ce96 --- /dev/null +++ b/lab 1/5.cpp @@ -0,0 +1,61 @@ +#include +#include + +class BankAccount { +protected: + std::string account_number; + double balance; + +public: + BankAccount(std::string account_number, double balance = 0) + : account_number(account_number), balance(balance) {} + + void deposit(double amount) { + if (amount > 0) { + balance += amount; + std::cout << "Deposited " << amount << " to account " << account_number << std::endl; + } else { + std::cout << "Invalid deposit amount" << std::endl; + } + } + + void withdraw(double amount) { + if (amount > 0 && amount <= balance) { + balance -= amount; + std::cout << "Withdrew " << amount << " from account " << account_number << std::endl; + } else { + std::cout << "Insufficient funds or invalid amount" << std::endl; + } + } + + void transfer(BankAccount& other, double amount) { + if (amount > 0 && amount <= balance) { + balance -= amount; + other.deposit(amount); + std::cout << "Transferred " << amount << " from account " << account_number << " to account " << other.account_number << std::endl; + } else { + std::cout << "Insufficient funds or invalid amount" << std::endl; + } + } + + void display() const { + std::cout << "Account Number: " << account_number << ", Balance: " << balance << std::endl; + } +}; + +int main() { + BankAccount account1("123456", 800); + BankAccount account2("654321", 3000); + + account1.display(); + account2.display(); + + account1.deposit(1200); + account1.withdraw(1000); + account1.transfer(account2, 1000); + + account1.display(); + account2.display(); + + return 0; +} \ No newline at end of file diff --git "a/\320\224\320\276\320\272\321\203\320\274\320\265\320\275\321\202 Microsoft Word.docx" "b/\320\224\320\276\320\272\321\203\320\274\320\265\320\275\321\202 Microsoft Word.docx" new file mode 100644 index 0000000..7b74fc5 Binary files /dev/null and "b/\320\224\320\276\320\272\321\203\320\274\320\265\320\275\321\202 Microsoft Word.docx" differ