当某天设置为月份的第一天并递减时,它应该成为上个月的最后一天,如何解决这个问题?

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?

这是我第一次尝试这样的问题。我很难解决这个问题,因为由于一些 reasons.Can 任何人都可以帮助我如何使用递减运算符,因为我不知道在哪里以及如何添加此类运算符以获得理想的输出。我已经晚了两天提交这个作业:(

#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;

}

你基本上可以用增量运算符做同样的事情,但要倒着做。递减的 C++ 运算符是 --variable 因此代码如下所示

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