Разработать класс содержащий перегрузку операторов - C#

Узнай цену своей работы

Формулировка задачи:

Создать класс Money, содержащий следующие члены класса: +1. Поля: •int first;//номинал купюры •int second; //количество купюр +2. Конструктор, позволяющий создать экземпляр класса с заданными значениям полей. +3. Методы, позволяющие: •вывести номинал и количество купюр; •определить, хватит ли денежных средств на покупку товара на сумму N рублей. •определить, сколько штук товара стоимости n рублей можно купить на имеющиеся денежные средства. +4. Свойство: •позволяющее получить - установить значение полей (доступное для чтения и записи); •позволяющее расчитатать сумму денег (доступное только для чтения). +5. Индексатор, позволяющий по индексу 0 обращаться к полю first, по индексу 1 – к полю second, при других значениях индекса выдается сообщение об ошибке. +-6. Перегрузку: •операции ++ (--): одновременно увеличивает (уменьшает) значение полей first и second; •операции !: возвращает значение true, если поле second не нулевое, иначе false; •операции бинарный +: добавляет к значению поля second значение скаляра.
У меня получилось так:
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace prakt_10
  8. {
  9. class Program
  10. {
  11. class Money
  12. {
  13. private int first;
  14. private int second;
  15. public Money(int first, int second)
  16. {
  17. this.first = first;
  18. this.second = second;
  19. }
  20. // methods
  21. public void Show()
  22. {
  23. Console.WriteLine("first: {0}, second: {1}", this.first, this.second);
  24. }
  25. public void Enough_Deficiency(int price) // enough or not enough
  26. {
  27. if (this.first * this.second >= price)
  28. {
  29. Console.WriteLine("Enough funds.");
  30. double numObj = this.first * this.second / price;
  31. numObj = Convert.ToInt16(Math.Floor(numObj)); // rounded <-
  32. Console.WriteLine("Funds enough to buy {0} objects", numObj);
  33. }
  34. else
  35. {
  36. Console.WriteLine("Insufficiently!");
  37. }
  38. }
  39. // properties
  40. public int values_first
  41. {
  42. get { return this.first; }
  43. set { this.first = value; }
  44. }
  45. public int values_second
  46. {
  47. get { return this.second; }
  48. set { this.second = value; }
  49. }
  50. public int Cash
  51. {
  52. get { return this.first * this.second; }
  53. }
  54. public int this[int i]
  55. {
  56. get
  57. {
  58. if (i == 0)
  59. { return this.first; }
  60. else
  61. {
  62. if (i == 1)
  63. { return this.second; }
  64. else
  65. {
  66. Console.WriteLine("Error! Invalid index.");
  67. return -1;
  68. }
  69. }
  70. }
  71. }
  72. }
  73. // owerload
  74. /*
  75. public static Money operator ++(Money M)
  76. {
  77. Money M1 = new Money(M.values_first *= 10, M.values_second *= 10);
  78. return M1;
  79. }
  80. public static Money operator --(Money M)
  81. {
  82. Money M1 = new Money(M.values_first /= 10, M.values_second /= 10);
  83. return M1;
  84. }
  85. public static Money operator !(Money M)
  86. {
  87. bool cash = false;
  88. if (M.values_second > 0)
  89. {
  90. cash = true;
  91. }
  92. return cash;
  93. }
  94. public static Money operator +(Money M, int skal)
  95. {
  96. Money M1 = new Money(M.values_first, M.values_second * skal);
  97. return M1;
  98. }
  99. */
  100.  
  101. static void Main(string[] args)
  102. {
  103. int first = int.Parse(Console.ReadLine());
  104. int second = int.Parse(Console.ReadLine());
  105. int price = int.Parse(Console.ReadLine());
  106. Money M1 = new Money(first, second);
  107. // tests
  108. M1.Show();
  109. M1.Enough_Deficiency(price);
  110. Console.WriteLine(M1.Cash);
  111. M1.values_first = 100;
  112. M1.values_second = 100;
  113. M1.Show();
  114. Console.ReadKey();
  115. }
  116. }
  117. }
Не могу понять в чем ошибка перегрузки операторов. Помогите плиз, как исправить?

Решение задачи: «Разработать класс содержащий перегрузку операторов»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace prakt_10
  9. {
  10.     class Money
  11.     {
  12.         private int first;
  13.         private int second;
  14.  
  15.         public Money(int first, int second)
  16.         {
  17.             this.first = first;
  18.             this.second = second;
  19.         }
  20.  
  21.         // methods
  22.         public void Show()
  23.         {
  24.             Console.WriteLine("first: {0}, second: {1}", this.first, this.second);
  25.         }
  26.  
  27.         public void Enough_Deficiency(int price)        // enough or not enough
  28.         {
  29.             if (this.first * this.second >= price)
  30.             {
  31.                 Console.WriteLine("Enough funds.");
  32.  
  33.                 double numObj = this.first * this.second / price;
  34.                 numObj = Convert.ToInt16(Math.Floor(numObj));       // rounded <-
  35.  
  36.                 Console.WriteLine("Funds enough to buy {0} objects", numObj);
  37.             }
  38.  
  39.             else
  40.             {
  41.                 Console.WriteLine("Insufficiently!");
  42.             }
  43.         }
  44.  
  45.         // properties
  46.         public int values_first
  47.         {
  48.             get { return this.first; }
  49.             set { this.first = value; }
  50.         }
  51.  
  52.         public int values_second
  53.         {
  54.             get { return this.second; }
  55.             set { this.second = value; }
  56.         }
  57.  
  58.         public int Cash
  59.         {
  60.             get { return this.first * this.second; }
  61.         }
  62.  
  63.         public int this[int i]
  64.         {
  65.             get
  66.             {
  67.                 if (i == 0)
  68.                 { return this.first; }
  69.  
  70.                 else
  71.                 {
  72.                     if (i == 1)
  73.                     { return this.second; }
  74.  
  75.                     else
  76.                     {
  77.                         Console.WriteLine("Error! Invalid index.");
  78.                         return -1;
  79.                     }
  80.                 }
  81.             }
  82.  
  83.         }
  84.  
  85.         public static Money operator ++(Money M)
  86.         {
  87.             Money M1 = new Money(M.values_first *= 10, M.values_second *= 10);
  88.             return M1;
  89.         }
  90.  
  91.         public static Money operator --(Money M)
  92.         {
  93.             Money M1 = new Money(M.values_first /= 10, M.values_second /= 10);
  94.             return M1;
  95.         }
  96.  
  97.         public static bool operator !(Money M)
  98.         {
  99.             bool cash = false;
  100.             if (M.values_second > 0)
  101.             {
  102.                 cash = true;
  103.             }
  104.  
  105.             return cash;
  106.         }
  107.  
  108.         public static Money operator +(Money M, int skal)
  109.         {
  110.             Money M1 = new Money(M.values_first, M.values_second * skal);
  111.             return M1;
  112.         }
  113.  
  114.  
  115.  
  116.         class test
  117.         {
  118.             static void Main(string[] args)
  119.             {
  120.                 int first = int.Parse(Console.ReadLine());
  121.                 int second = int.Parse(Console.ReadLine());
  122.                 int price = int.Parse(Console.ReadLine());
  123.  
  124.                 Money M1 = new Money(first, second);
  125.  
  126.                 // tests
  127.                 M1.Show();
  128.                 M1.Enough_Deficiency(price);
  129.                 Console.WriteLine(M1.Cash);
  130.  
  131.                 M1.values_first = 100;
  132.                 M1.values_second = 100;
  133.                 M1.Show();
  134.  
  135.                 Console.ReadKey();
  136.             }
  137.         }
  138.     }
  139. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы