Реализация абстрактного класса Pair и его наследников
Вот полная реализация задачи на C#:
using System;
using System.Collections.Generic;
// Абстрактный класс Pair
public abstract class Pair
{
public abstract void Display();
public abstract Pair Add(Pair other);
public abstract Pair Subtract(Pair other);
public abstract Pair Multiply(Pair other);
}
// Класс Money (деньги)
public class Money : Pair
{
public int Rubles { get; set; }
public int Kopecks { get; set; }
public Money(int rubles, int kopecks)
{
Rubles = rubles;
Kopecks = kopecks;
Normalize();
}
private void Normalize()
{
if (Kopecks >= 100)
{
Rubles += Kopecks / 100;
Kopecks %= 100;
}
else if (Kopecks < 0)
{
Rubles -= (-Kopecks) / 100 + 1;
Kopecks = 100 - (-Kopecks % 100);
}
}
public override void Display()
{
Console.WriteLine($"{Rubles} руб. {Kopecks:D2} коп.");
}
public override Pair Add(Pair other)
{
if (other is Money money)
{
int totalRubles = Rubles + money.Rubles;
int totalKopecks = Kopecks + money.Kopecks;
return new Money(totalRubles, totalKopecks);
}
throw new ArgumentException("Невозможно сложить Money с другим типом Pair");
}
public override Pair Subtract(Pair other)
{
if (other is Money money)
{
int totalRubles = Rubles - money.Rubles;
int totalKopecks = Kopecks - money.Kopecks;
return new Money(totalRubles, totalKopecks);
}
throw new ArgumentException("Невозможно вычесть другой тип Pair из Money");
}
public override Pair Multiply(Pair other)
{
if (other is Money money)
{
int totalKopecks = (Rubles * 100 + Kopecks) * (money.Rubles * 100 + money.Kopecks);
return new Money(0, totalKopecks); // Конструктор сам нормализует
}
throw new ArgumentException("Невозможно умножить Money на другой тип Pair");
}
}
// Класс Complex (комплексное число)
public class Complex : Pair
{
public double Real { get; set; }
public double Imaginary { get; set; }
public Complex(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public override void Display()
{
if (Imaginary >= 0)
Console.WriteLine($"{Real} + {Imaginary}i");
else
Console.WriteLine($"{Real} - {-Imaginary}i");
}
public override Pair Add(Pair other)
{
if (other is Complex complex)
{
return new Complex(Real + complex.Real, Imaginary + complex.Imaginary);
}
throw new ArgumentException("Невозможно сложить Complex с другим типом Pair");
}
public override Pair Subtract(Pair other)
{
if (other is Complex complex)
{
return new Complex(Real - complex.Real, Imaginary - complex.Imaginary);
}
throw new ArgumentException("Невозможно вычесть другой тип Pair из Complex");
}
public override Pair Multiply(Pair other)
{
if (other is Complex complex)
{
double real = Real * complex.Real - Imaginary * complex.Imaginary;
double imaginary = Real * complex.Imaginary + Imaginary * complex.Real;
return new Complex(real, imaginary);
}
throw new ArgumentException("Невозможно умножить Complex на другой тип Pair");
}
}
// Класс Series (набор)
public class Series
{
private List<Pair> items = new List<Pair>();
public void AddItem(Pair item)
{
items.Add(item);
}
public void DisplayAll()
{
foreach (var item in items)
{
item.Display();
}
}
public Pair this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
public int Count => items.Count;
}
// Демонстрационная программа
class Program
{
static void Main()
{
// Создаем объекты Money
Money money1 = new Money(10, 50);
Money money2 = new Money(5, 75);
Console.WriteLine("Деньги 1:");
money1.Display();
Console.WriteLine("Деньги 2:");
money2.Display();
// Арифметические операции с Money
Console.WriteLine("\nСложение денег:");
Money sumMoney = (Money)money1.Add(money2);
sumMoney.Display();
Console.WriteLine("Вычитание денег:");
Money diffMoney = (Money)money1.Subtract(money2);
diffMoney.Display();
Console.WriteLine("Умножение денег:");
Money productMoney = (Money)money1.Multiply(money2);
productMoney.Display();
// Создаем объекты Complex
Complex complex1 = new Complex(3, 4);
Complex complex2 = new Complex(1, -2);
Console.WriteLine("\nКомплексное число 1:");
complex1.Display();
Console.WriteLine("Комплексное число 2:");
complex2.Display();
// Арифметические операции с Complex
Console.WriteLine("\nСложение комплексных чисел:");
Complex sumComplex = (Complex)complex1.Add(complex2);
sumComplex.Display();
Console.WriteLine("Вычитание комплексных чисел:");
Complex diffComplex = (Complex)complex1.Subtract(complex2);
diffComplex.Display();
Console.WriteLine("Умножение комплексных чисел:");
Complex productComplex = (Complex)complex1.Multiply(complex2);
productComplex.Display();
// Работа с классом Series
Series series = new Series();
series.AddItem(money1);
series.AddItem(money2);
series.AddItem(complex1);
series.AddItem(complex2);
Console.WriteLine("\nСодержимое Series:");
series.DisplayAll();
// Демонстрация индексатора
Console.WriteLine("\nЭлемент Series с индексом 2:");
series[2].Display();
}
}
Описание реализации:
-
Абстрактный класс Pair:
- Содержит абстрактные методы для арифметических операций и вывода на экран
- Служит базовым классом для Money и Complex
-
Класс Money:
- Хранит рубли и копейки как целые числа
- Реализует методы сложения, вычитания и умножения денежных сумм
- Метод Display выводит сумму в формате "X руб. YY коп."
- Включает нормализацию копеек (чтобы их значение всегда было в диапазоне 0-99)
-
Класс Complex:
- Хранит действительную и мнимую части комплексного числа
- Реализует арифметические операции для комплексных чисел
- Метод Display выводит число в формате "a + bi" или "a - bi"
-
Класс Series:
- Содержит список объектов типа Pair
- Имеет методы для добавления элементов и вывода всех элементов
- Реализует индексатор для доступа к элементам по индексу
-
Демонстрационная программа:
- Создает объекты Money и Complex
- Демонстрирует все арифметические операции
- Показывает работу с классом Series
- Использует все методы классов
Программа демонстрирует полиморфизм, работая с объектами разных классов через базовый класс Pair.