Перегруженные операции и индексаторы - C#
Формулировка задачи:
Привет всем! Проблема такова. Задали контрольную, в консоли создать абстрактный класс с методами, контрольная выполнена. Но преподаватель затребовал усложнения задачи, а именно - добавить перегруженные операции, индексаторы, обработку исключений, конструкторы с параметрами и без них. А с этим проблема, так как C# изучаем всего-ничего по времени. Да и время поджимает, в понедельник сдача. Помогите, пожалуйста! Код прилагаю. Спасибо огромное.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ControlWork__2
{
abstract class Function
{
public abstract double Count(double x);
}
// ЛИНИЯ
class Line : Function
{
public readonly double A;
public readonly double B;
public Line(double a, double b)
{
A = a;
B = b;
}
public override double Count(double x)
{
return A * x + B;
}
}
// КУБ
class Kub : Function
{
public readonly double A;
public readonly double B;
public readonly double C;
public Kub(double a, double b, double c)
{
A = a;
B = b;
C = c;
}
public override double Count(double x)
{
return A * x * x + B * x + C;
}
}
// Парабола
class Parabola : Function
{
public readonly double A;
public readonly double B;
public Parabola(double a,double b)
{
A = a;
B = b;
}
public override double Count(double x)
{
return A * x * x + B;
}
}
class Program
{
static void Main(string[] args)
{
Function[] func = new Function[3];
func[0] = new Line(2, 3);
func[1] = new Kub(2, 3, 4);
func[2] = new Parabola(2,3);
double x = 3.6;
foreach (Function f in func)
Console.WriteLine("Значение функции {0} для x = {1} равно {2}", f.GetType(), x, f.Count(x));
Console.ReadLine();
}
}
}Решение задачи: «Перегруженные операции и индексаторы»
textual
Листинг программы
abstract class Function
{
public abstract double Calc(double x);
public virtual double this[double x]
{
get { return Calc(x); }
}
public static Function operator +(Function f1, Function f2)
{
return new SumFunction(f1, f2);
}
}
/// <summary>
/// Сумма функций
/// </summary>
class SumFunction : Function
{
public readonly Function[] Functions;
public SumFunction(params Function[] functions)
{
Functions = functions;
}
public override double Calc(double x)
{
double res = 0d;
foreach (var f in Functions)
res += f[x];
return res;
}
}
class Constant : Function
{
public readonly double A;
public Constant()
{
}
public Constant(double a)
{
A = a;
}
public override double Calc(double x)
{
return A;
}
}
// ЛИНИЯ
class Linear : Function
{
public readonly double A;
public Linear()
{
}
public Linear(double a)
{
A = a;
}
public override double Calc(double x)
{
return A * x;
}
}
// КУБ
class Cubic : Function
{
public readonly double A;
public Cubic()
{
}
public Cubic(double a)
{
A = a;
}
public override double Calc(double x)
{
return A * x * x * x;
}
}
// Парабола
class Quadratic : Function
{
public readonly double A;
public Quadratic()
{
}
public Quadratic(double a)
{
A = a;
}
public override double Calc(double x)
{
return A * x * x;
}
}
class Program
{
static void Main(string[] args)
{
Function[] func = new Function[4];
func[0] = new Constant(3);
func[1] = new Linear(-3);
func[2] = new Quadratic(2);
func[3] = new Cubic(1);
double x = 3.6;
foreach (Function f in func)
CalcAndOutput(f, x, f.GetType().Name);
//функция x^3 + 2*x^2 - 3*x + 3
var sum = new Cubic(1) + new Quadratic(2) + new Linear(-3) + new Constant(3);
CalcAndOutput(sum, x, "x^3 + 2*x^2 - 3*x + 3");
Console.ReadLine();
}
private static void CalcAndOutput(Function f, double x, string name)
{
try
{
Console.WriteLine("Значение функции {0} для x = {1} равно {2}", name, x, f[x]);
}
catch (Exception ex)
{
Console.WriteLine("Значение функции {0} не может быть вычислено для аргумента {1}", name, x);
}
}
}