• Предмет: Информатика
  • Автор: Kukuwka0Ha0DepeBe
  • Вопрос задан 2 месяца назад

С++
Завдання №1
Створіть клас Date, який буде містити інформацію
про дату (день, місяць, рік).
За допомогою механізму перевантаження операторів,
визначте операцію різниці двох дат (результат у вигляді
кількості днів між датами), а також операцію збільшення
дати на певну кількість днів.
Завдання №2.
Додати в рядковий клас функцію, яка створює рядок,
що містить перетин двох рядків, тобто загальні символи
для двох рядків.
Наприклад, результатом перетину рядків «sdqcg»
«rgfas34» буде рядок «sg». Для реалізації функції перевантажити оператор «*» (бінарне множення).

Ответы

Ответ дал: Davinchii
0

Завдання 1.

#include <iostream>

class Date {

private:

int day;

int month;

int year;

public:

Date(int d, int m, int y) : day(d), month(m), year(y) {}

int operator-(const Date& other) {

int totalDays = 0;

// Перевірка років

for (int i = other.year; i < year; i++) {

totalDays += isLeapYear(i) ? 366 : 365;

}

// Перевірка місяців

for (int i = 1; i < month; i++) {

totalDays += getDaysInMonth(i, year);

}

totalDays += day;

// Віднімання днів з другої дати

for (int i = 1; i < other.month; i++) {

totalDays -= getDaysInMonth(i, other.year);

}

totalDays -= other.day;

return totalDays;

}

Date operator+(int days) {

Date result = *this;

int daysToAdd = days;

while (daysToAdd > 0) {

int daysInMonth = getDaysInMonth(result.month, result.year);

if (result.day + daysToAdd > daysInMonth) {

daysToAdd -= (daysInMonth - result.day + 1);

result.day = 1;

if (result.month == 12) {

result.month = 1;

result.year++;

} else {

result.month++;

}

} else {

result.day += daysToAdd;

daysToAdd = 0;

}

}

return result;

}

private:

bool isLeapYear(int year) {

return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

}

int getDaysInMonth(int month, int year) {

if (month == 2) {

return isLeapYear(year) ? 29 : 28;

} else if (month == 4 || month == 6 || month == 9 || month == 11) {

return 30;

} else {

return 31;

}

}

};

int main() {

Date d1(1, 1, 2023);

Date d2(1, 2, 2023);

int difference = d2 - d1;

std::cout << "Difference in days: " << difference << std::endl;

Date d3 = d1 + 10;

std::cout << "New date: " << d3.day << "." << d3.month << "." << d3.year << std::endl;

return 0;

}

_____________________________

Завдання 2.

#include <iostream>

#include <string>

class StringIntersection {

private:

std::string str;

public:

StringIntersection(const std::string& s) : str(s) {}

std::string operator*(const StringIntersection& other) {

std::string result;

for (char c : str) {

if (other.str.find(c) != std::string::npos) {

result += c;

}

}

return result;

}

};

int main() {

StringIntersection s1("sdqcg");

StringIntersection s2("rgfas34");

std::string intersection = s1 * s2;

std::cout << "Intersection: " << intersection << std::endl;

return 0;

}

Вас заинтересует