Перегрузка унарного оператора - C#
Формулировка задачи:
Добрый день, проходя курс ООП столкнулся с проблемой при перегрузке инкремента, декремента.
Используется перегруженый конструктор копирования, при использовании варианта перегрузки что закоментирован,не работает постфиксная форма(работает как префиксня) при этом в остальных случаях все нормально.
Класс
Main
при использовании не за комментированного варианта все работает.
По идее первый вариант лутше т.к. не надо создвать новый обьект(а следовательно использовать память, процесорное время), но почему он некоректно работает (с конструктором копирования)?
Спасибо)
class Date :IComparable { private int _day, _month, _year; #region properties get public int Day { get { return _day; } } public int Month { get { return _month; } } public int Year { get { return _year; } } #endregion #region constructors public Date() { _day = DateTime.Today.Day; _month = DateTime.Today.Month; _year = DateTime.Today.Year; } public Date(int d, int m, int y) { _day = d; _month = m; _year = y; check_DMY(); } public Date(Date previousDate) { this._day = previousDate.Day; this._month = previousDate.Month; this._year = previousDate.Year; } #endregion private void check_DMY() { int _years_from_mouth, dictionaryValue; bool check_ok; Dictionary<int, int> mas_days = new Dictionary<int, int> { { 1, 31 }, { 2, 28 }, { 3, 31 }, { 4, 30 }, { 5, 31 }, { 6, 30 }, { 7, 31 }, { 8, 31 }, { 9, 30 }, { 10, 31 }, { 11, 30 }, { 12, 31 }}; check_ok = false; while (!check_ok) { if (this._year <= 0) throw new ArgumentException(); //Исключение надо исключение другое вібрать //опредление высокосного года if (this._year % 4 == 0) { mas_days[2] = 29; } //если количество месяцев >12 _years_from_mouth = 0; if (this._month > 12) { _years_from_mouth = this._month / 12; this._year += _years_from_mouth; this._month -= _years_from_mouth * 12; } else { if (this._month <= 0) { this._year--; this._month += 12; } } if (this._month > 0) { dictionaryValue = mas_days[this._month]; //число дней в месяце //если кол.дней > кол.дней в месяце if (this._day > dictionaryValue) { this._day -= dictionaryValue; this._month++; } else //если кол.дней < 1, и месяц не первый (0/2/2005) if (this._day < 1 && this._month > 1) { this._month--; this._day = mas_days[this._month]; } //если день соответствует диапазону 1-кол.дней в определенном мецяце, удовлетворяется условие выхода из цикла if (this._day >= 1 && this._day <= dictionaryValue && this._month <= 12) { check_ok = true; } } } } //public static Date operator ++(Date a) //{ // a._day+=1; // a.check_DMY(); // return a; //} //public static Date operator --(Date a) //{ // --a._day; // a.check_DMY(); // return a; //} public static Date operator ++(Date a) { return new Date(a.Day + 1, a.Month, a.Year); } public static Date operator --(Date a) { return new Date(a.Day - 1, a.Month, a.Year); } // Override the ToString() method to display data in the traditional format: public override string ToString() { string _sd, _sm; if (_day < 10) _sd = String.Format("0{0}", _day); else _sd = Convert.ToString(_day); if (_month < 10) _sm = String.Format("0{0}",_month); else _sm = Convert.ToString(_month); return (System.String.Format("{0}/{1}/{2}", _sd, _sm, _year)); } }
static void Main(string[] args) { try { Date date1 = new Date(); Console.WriteLine("\n----------------------------------"); Console.WriteLine("\nПрефикс ++"); Console.WriteLine("\n Date1= {0}", date1.ToString()); Date ndate=new Date(++date1); Console.WriteLine("\n Date1= {0}", date1.ToString()); Console.WriteLine("\n Daten= {0}", ndate.ToString()); Console.WriteLine("\n----------------------------------"); Console.WriteLine("\nПостфикс ++"); ndate = new Date(date1++); Console.WriteLine("\n Date1= {0}", date1.ToString()); Console.WriteLine("\n Daten= {0}", ndate.ToString()); } catch (ArgumentException e){ Console.Write("\n"+e.Message); Console.ReadKey(); } Console.ReadKey(); }
Решение задачи: «Перегрузка унарного оператора»
textual
Листинг программы
Date a = new Date(); Date b = ++a; Console.WriteLine(a); Console.WriteLine(b); // Изменяется a a++; Console.WriteLine(b); // Изменния будут видны и в b.
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д