Разработать класс содержащий перегрузку операторов - C#
Формулировка задачи:
Создать класс Money, содержащий следующие члены класса:
+1. Поля:
•int first;//номинал купюры
•int second; //количество купюр
+2. Конструктор, позволяющий создать экземпляр класса с заданными значениям полей.
+3. Методы, позволяющие:
•вывести номинал и количество купюр;
•определить, хватит ли денежных средств на покупку товара на сумму N рублей.
•определить, сколько штук товара стоимости n рублей можно купить на имеющиеся денежные средства.
+4. Свойство:
•позволяющее получить - установить значение полей (доступное для чтения и записи);
•позволяющее расчитатать сумму денег (доступное только для чтения).
+5. Индексатор, позволяющий по индексу 0 обращаться к полю first, по индексу 1 – к полю second, при других значениях индекса выдается сообщение об ошибке.
+-6. Перегрузку:
•операции ++ (--): одновременно увеличивает (уменьшает) значение полей first и second;
•операции !: возвращает значение true, если поле second не нулевое, иначе false;
•операции бинарный +: добавляет к значению поля second значение скаляра.
У меня получилось так:
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Text;
- using System.Threading.Tasks;
- namespace prakt_10
- {
- class Program
- {
- class Money
- {
- private int first;
- private int second;
- public Money(int first, int second)
- {
- this.first = first;
- this.second = second;
- }
- // methods
- public void Show()
- {
- Console.WriteLine("first: {0}, second: {1}", this.first, this.second);
- }
- public void Enough_Deficiency(int price) // enough or not enough
- {
- if (this.first * this.second >= price)
- {
- Console.WriteLine("Enough funds.");
- double numObj = this.first * this.second / price;
- numObj = Convert.ToInt16(Math.Floor(numObj)); // rounded <-
- Console.WriteLine("Funds enough to buy {0} objects", numObj);
- }
- else
- {
- Console.WriteLine("Insufficiently!");
- }
- }
- // properties
- public int values_first
- {
- get { return this.first; }
- set { this.first = value; }
- }
- public int values_second
- {
- get { return this.second; }
- set { this.second = value; }
- }
- public int Cash
- {
- get { return this.first * this.second; }
- }
- public int this[int i]
- {
- get
- {
- if (i == 0)
- { return this.first; }
- else
- {
- if (i == 1)
- { return this.second; }
- else
- {
- Console.WriteLine("Error! Invalid index.");
- return -1;
- }
- }
- }
- }
- }
- // owerload
- /*
- public static Money operator ++(Money M)
- {
- Money M1 = new Money(M.values_first *= 10, M.values_second *= 10);
- return M1;
- }
- public static Money operator --(Money M)
- {
- Money M1 = new Money(M.values_first /= 10, M.values_second /= 10);
- return M1;
- }
- public static Money operator !(Money M)
- {
- bool cash = false;
- if (M.values_second > 0)
- {
- cash = true;
- }
- return cash;
- }
- public static Money operator +(Money M, int skal)
- {
- Money M1 = new Money(M.values_first, M.values_second * skal);
- return M1;
- }
- */
- static void Main(string[] args)
- {
- int first = int.Parse(Console.ReadLine());
- int second = int.Parse(Console.ReadLine());
- int price = int.Parse(Console.ReadLine());
- Money M1 = new Money(first, second);
- // tests
- M1.Show();
- M1.Enough_Deficiency(price);
- Console.WriteLine(M1.Cash);
- M1.values_first = 100;
- M1.values_second = 100;
- M1.Show();
- Console.ReadKey();
- }
- }
- }
Не могу понять в чем ошибка перегрузки операторов. Помогите плиз, как исправить?
Решение задачи: «Разработать класс содержащий перегрузку операторов»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Text;
- using System.Threading.Tasks;
- namespace prakt_10
- {
- class Money
- {
- private int first;
- private int second;
- public Money(int first, int second)
- {
- this.first = first;
- this.second = second;
- }
- // methods
- public void Show()
- {
- Console.WriteLine("first: {0}, second: {1}", this.first, this.second);
- }
- public void Enough_Deficiency(int price) // enough or not enough
- {
- if (this.first * this.second >= price)
- {
- Console.WriteLine("Enough funds.");
- double numObj = this.first * this.second / price;
- numObj = Convert.ToInt16(Math.Floor(numObj)); // rounded <-
- Console.WriteLine("Funds enough to buy {0} objects", numObj);
- }
- else
- {
- Console.WriteLine("Insufficiently!");
- }
- }
- // properties
- public int values_first
- {
- get { return this.first; }
- set { this.first = value; }
- }
- public int values_second
- {
- get { return this.second; }
- set { this.second = value; }
- }
- public int Cash
- {
- get { return this.first * this.second; }
- }
- public int this[int i]
- {
- get
- {
- if (i == 0)
- { return this.first; }
- else
- {
- if (i == 1)
- { return this.second; }
- else
- {
- Console.WriteLine("Error! Invalid index.");
- return -1;
- }
- }
- }
- }
- public static Money operator ++(Money M)
- {
- Money M1 = new Money(M.values_first *= 10, M.values_second *= 10);
- return M1;
- }
- public static Money operator --(Money M)
- {
- Money M1 = new Money(M.values_first /= 10, M.values_second /= 10);
- return M1;
- }
- public static bool operator !(Money M)
- {
- bool cash = false;
- if (M.values_second > 0)
- {
- cash = true;
- }
- return cash;
- }
- public static Money operator +(Money M, int skal)
- {
- Money M1 = new Money(M.values_first, M.values_second * skal);
- return M1;
- }
- class test
- {
- static void Main(string[] args)
- {
- int first = int.Parse(Console.ReadLine());
- int second = int.Parse(Console.ReadLine());
- int price = int.Parse(Console.ReadLine());
- Money M1 = new Money(first, second);
- // tests
- M1.Show();
- M1.Enough_Deficiency(price);
- Console.WriteLine(M1.Cash);
- M1.values_first = 100;
- M1.values_second = 100;
- M1.Show();
- Console.ReadKey();
- }
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д