You are on page 1of 9

Міністерство освіти і науки України

Відокремлений структурний підрозділ


«Фаховий коледж інженерії, управління та землевпорядкування Національного
авіаційного університету»

ЗВІТ
з лабораторної роботи № 9 – 10
з дисципліни
“Об’єктно-орієнтоване програмування”

Виконав:
студент групи 306 -ІПЗ
Сопіженко Денис

Перевірив викладач:
Наталія РЯБЧУК

м. Київ 2023

17
Тема роботи: реалізація множинного успадкування
Мета роботи:
● вивчити принципи та правила реалізації множинного успадкування В
мові С++;
● закріпити на практиці знання протоколу успадкування;
● набути вміння використовувати успадкування для побудови
ієрархічних класових структур для розв’язання різних класів задач.
Завдання
Створення, компіляція, відладка та виконання програми, в якій реалізується і
тестується певна ієрархія кспадкування класів. Результатом виконання
лабораторної роботи має бути демонстрація коректної логіки функціонування
методів похідного класу в програмі.

#include <iostream>
#include <string>

Class Country {
Protected:
Std::string name;
Int population;
Double area;

Public:
// Default constructor
Country() : name(«Ukraine»), population(45000000), area(603500) {}

// Initialization constructor with user-defined arguments


Country(const std::string& countryName, int pop, double a) :
name(countryName), population(pop), area(a) {}

27
// Copy constructor
Country(const Country& other) : name(other.name),
population(other.population), area(other.area) {}

// Unary operator «-« (changes the sign of the population)


Country operator-() const {
Country result(*this);
Result.population = -result.population;
Return result;
}

// Binary operator «+» (adds the area)


Country operator+(const Country& other) const {
Country result(*this);
Result.area += other.area;
Return result;
}

// Binary operator «-« (subtracts the area)


Country operator-(const Country& other) const {
Country result(*this);
Result.area -= other.area;
Return result;
}

// Binary operator «==» (compares countries based on population and area)


Bool operator==(const Country& other) const {
Return (population == other.population) && (area == other.area);
}

37
// Method to check if the country exists based on user input
Void checkExistence(int inputPopulation, double inputArea) {
If (inputPopulation == population && inputArea == area) {
Std::cout << «The country exists\n»;
} else {
Std::cout << «Does not exist\n»;
}
}

// Destructor
Virtual ~Country() {
Std::cout << «Destructor executed for the country « << name <<
std::endl;
}
};

Class Capital : public Country {


Private:
Std::string capitalName;

Public:
// Default constructor
Capital() : capitalName(«Kyiv») {}

// Initialization constructor with user-defined arguments


Capital(const std::string& countryName, int pop, double a, const
std::string& capital)
: Country(countryName, pop, a), capitalName(capital) {}

// Method to display information about the capital

47
Void displayCapitalInfo() const {
Std::cout << «The capital of « << name << « is « << capitalName <<
std::endl;
}
};

Class President : public Country {


Private:
Std::string presidentName;

Public:
// Default constructor
President() : presidentName(«Yanukovych») {}

// Initialization constructor with user-defined arguments


President(const std::string& countryName, int pop, double a, const
std::string& president)
: Country(countryName, pop, a), presidentName(president) {}

// Method to display information about the president


Void displayPresidentInfo() const {
Std::cout << «The president of « << name << « was « << presidentName
<< std::endl;
}
};

// DisplayInfo class inherits from both Capital and President


Class DisplayInfo : public Capital, public President {
Public:
// Method to display information inherited from both base classes

57
Void displayAllInfo() const {
displayCapitalInfo();
displayPresidentInfo();
}
};

Class User {
Public:
Void enterPassword() {
Std::string password;
Std::cout << «Enter password: «;
Std::cin >> password;
If (password == «admin123») {
Int created;
Std::cout << «Enter the 'created' number (1991): «;
Std::cin >> created;
If (created == 1991) {
Std::cout << «Access granted as Admin.\n»;
// Perform Admin-specific actions here
} else {
Std::cout << «Access denied.\n»;
}
} else {
Std::cout << «Access granted as User.\n»;
// Perform User-specific actions here
}
}
};

Int main() {

67
User user;
User.enterPassword();

// Creating objects of the Country class using different constructors


Country defaultCountry; // Default constructor

Std::string customName;
Int customPopulation;
Double customArea;

// User input for other countries


Std::cout << «Enter the country name: «;
Std::getline(std::cin, customName);

Std::cout << «Enter the population: «;


Std::cin >> customPopulation;

Std::cout << «Enter the area in km²: «;


Std::cin >> customArea;

Country customCountry(customName, customPopulation, customArea); //


Initialization constructor

Country copiedCountry = defaultCountry; // Copy constructor

// Displaying results for verification


Std::cout << «For the country 'Ukraine': «;
defaultCountry.checkExistence(45000000, 603500);

std::cout << «For the country '» << customName << «': «;

77
customCountry.checkExistence(customPopulation, customArea);

std::cout << «For the copied country: «;


copiedCountry.checkExistence(45000000, 603500);

// Overloaded operators
Country negatedCountry = -defaultCountry; // Unary operator «-«
Country combinedCountry = defaultCountry + customCountry; // Binary
operator «+»
Country subtractedCountry = defaultCountry – customCountry; // Binary
operator «-«
Bool isEqual = defaultCountry == copiedCountry; // Binary operator «==»

// Creating objects of the Capital and President classes


Capital capitalCity(«CountryWithCapital», 1000000, 1000, «Kyiv»);
capitalCity.displayCapitalInfo();

President countryPresident(«CountryWithPresident», 5000000, 5000,


«Yanukovych»);
countryPresident.displayPresidentInfo();

// Creating an object of the DisplayInfo class


DisplayInfo displayInfoObject;
displayInfoObject.displayAllInfo();

return 0;
}
Тут було реалізовно

87
Контрольні запитання
1)Множинне успадкування – це змога классу успадковувати властивості
від декількох класів водночас. Його використовують для задання класу
успадкування властивостей з множини інших класі для скорочення
манаіпуляцій над кодом
2)Існує три кваліфікатори: public, protected та privat
Public – при передачі зберігає усі права доступу
Protected – залишає приватні елементи похідного класу приватними, а
відкриті обертає на захищені
Privat – Перетворює усі елементи на приватні
3)Конструктори викликаються послідовно, від Базового до
Наслідуючого, кожен ланцюг реалізує лише власні данні. При реалізації класів
базовий клас може викликати наступний клас явно або не явно, активація
деструктора запускає процес зчитування класів в зворотньому порядку.
4)Проблема реалізації множинного класу може виникнути в випадку
якщо до одного файла булуть закріплені два інших щ однаковими іменами, для
уникнення цієї проблеми потрібно вказувати кожному файлу власне ім'я, абоє
робити різні нумерації.

Висновки
В ході даної лабораторної роботи ми провели розділення класів методом
множинного успадкування

97

You might also like