Home > Enterprise >  how to solve this question when a day is set to the first day of the month and decremented, it shoul
how to solve this question when a day is set to the first day of the month and decremented, it shoul

Time:05-30

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;

}

CodePudding user response:

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);
}
  • Related