简体   繁体   中英

how to solve this question when a day is set to the first day of the month and decremented, it should become the last day of the previous month?

This is my first time trying such question .It has been so difficult for me to solve this question as I wasn't able to attend my classes when this was taught due to some reasons.Can anyone help me how do I use decrement operators as I have no idea where and how to add such operators to get the desirable output. I am already two days late for submitting this assignment :(

#include <iostream>
using namespace std;

class Date{
   private:
      int day;
      int month;
      int year;

   public:
   Date()
   {
        day;
        month;
        year;
   }
      Date(int d, int m , int y)
      {
         day = d;
       month = m;
        year = y;
      }
       void displayDate() {
         cout << "Day: " << day << " Month:" << month <<" Year:"<<year<<endl;
      }
// overloaded prefix ++ operator
      Date operator++ () {
         ++day;
         ++year;
         ++month;

         if(day >= 31) {

            day -= 31;
         }
        if (month>=12)
        {
         month -= 12;
         }
         return Date(day, month,year);
      }
      };




int main ()
{
      int day;
      int month;
      int year;
      string month_name[20] = {"January","February","March","April","May","June","July","August","September","October","November","December"};

     do{
      cout << "Enter a day: ";
      cin >> day;

         if (day > 31 || day < 1)
         cout<<"This is invalid "<<endl;
        }

     while (day > 31 || day < 1);

     do{
      cout << "Enter a month: " ;
      cin >> month;

         if (month > 12 || month < 1)
         cout<<"This is invalid "<<endl;
       }

     while (month > 12 || month < 1);
      cout << "Enter a year: ";
     cin >> year;


    cout << month << "/" << day << "/" << year << endl;
    cout << month_name[month-1]<< " " << day << ", " << year << endl;
    cout << day << " " <<  month_name[month-1] << "," << year << endl;



   Date D1(day,month,year);
   ++D1;            // increment D1
   D1.displayDate();   // display D1
   ++D1;               // increment of D1 again
   D1.displayDate();        // display D1

   return 0;

}

You can basically do the same thing with the increment operator but do it backwards. The C++ operator for decrement is --variable so the code would look as follows

Date operator--(){
    --day;
    --year;
    --month;
    if(day <= 0) 
    {
        day += 31;
    }
    if (month<=0)
    {
        month += 12;
    }
    return Date(day, month,year);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM