#include<iostream>
#include<time.h>
using namespace std;

class Calendar
{
      int count;
      public:
      int year;
      int month;
      int date;
      Calendar& operator++();
      Calendar& operator--();
      Calendar()
      {
                count=0;
                year=rand()%300+1900;
                month=rand()%12+1; 
                date=rand()%30+1;
                while(month==2&&date>28)
                {
                    month=rand()%12+1; 
                    date=rand()%30+1;
                } 
                }
      void show()
      {
      printf("+%d-%2d-%2d+  ",year,month,date); count++;
      if(count%5==0)cout<<endl;
            } 
      };
      

Calendar& Calendar::operator++()
{  //大1 3 5 7 8 10 12  小 2 4 6 11 9 
      switch(month)
      {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            date++; 
            if(date>31){month++; date=1;} 
            break; 
            case 12:
            date++; 
            if(date>31){month=1; date=1; year++;} 
            break; 
            case 2:
            date++;
            if(date>28){month++; date=1;} 
            break; 
            case 4:
            case 6: 
            case 9:
            case 11:
            date++; 
            if(date>30){month++; date=1;} 
            break; 
            } 
      return *this; 
}


Calendar& Calendar::operator--()
{  //大1 3 5 7 8 10 12  小 2 4 6 11 9 
      switch(month)
      {
            case 1:
            date--; 
            if(date<1){month=12; date=31; year--;} 
            break;
            case 12:
            case 10:
            case  8:
            case  7:
            case  5:
            date--; 
            if(date<1){month--; date=30;} 
            break;
            case 11:
            case  9:
            case  6:
            case  4:
            case  2:
            date--; 
            if(date<1){month--; date=31;} 
            break;
            case  3:
            date--; 
            if(date<1){month--; date=28;} 
            break;    
            } 
      return *this; 
}

int main (void)
{
    srand(time(NULL)); 
    Calendar d; 
    d.show(); 
    cout<<"加365次"<<endl; 
    for(int cc=1; cc<=365; cc++)
    { 
    (++d).show(); 
    } 
    cout<<"減365次"<<endl; 
    for(int cc=1; cc<=365; cc++)
    { 
    (--d).show(); 
    } 

    system("pause"); 
    }

 

[C++] 運算子多載左移跟右移-製作日期遞增或遞減的功能  

周宇若 發表在 痞客邦 留言(0) 人氣()