Xây dựng lớp date trong C++


Xây dựng lớp date1 có các thành phần sau:


- Các thuộc tính : day, month, year
- Hàm thiết lập có tham số mặc định
- Hàm kiểm tra năm nhuận
- Hàm kiểm tra ngày cuối tháng
- Nạp chồng toán tử tăng (++)
- Nạp chồng toán tử (+ =)
- Nạp chồng toán tử xuất (<<)


Viết chương trình kiểm tra


#include <iostream.h>
#include <conio.h>
class date1
{
  private:
    int day;
    int month;
    int year;
    static const int days[];
    void helpIncrement();
  public:
    date1(int d=1,int m=1,int y=1900);
    void setdate(int d,int m,int y);
    date1 &operator++();
    date1 &operator+=(int addday);
    bool leapyear(int y);//kiem tra nam nhuan
    bool endofmonth(int d);//kiem tra ngay cuoi thang
    friend ostream & operator<<(ostream & out,date1 &date);

};

const int date1::days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

date1::date1(int d,int m,int y)
{
   setdate(d,m,y);
}

void date1::setdate(int d,int m,int y)
{
    month=(m>=1 && m<=12)? m:1;
    year=(y>=1900 && y<=2100)?y:1900;
      if( month==2 && leapyear(y))
        day=(d>=1 && d<=29)? d:1;
      else
        day=(d>=1 && d<=days[month])? d:1;
}

bool date1::leapyear(int y)
{
       if ((y%400 ==0)||(y%100 !=0 && y%4==0))
           return true;
       else
           return false;
}

bool date1::endofmonth(int d)
{
     if(month==2 && leapyear(year))
       return d==29;
     else
       return d==days[month];
}

void date1::helpIncrement()
{
    if(month==2 && leapyear(year))//ngay cuoi nam
       {
          day=1;
          month=1;
          ++year;
       }
   else
     if(endofmonth(day))//ngay cuoi thang
       {
        day=1;
        ++month;
       }
     else
       ++day;
}

date1 &date1::operator++()
{
   helpIncrement();
   return * this;
}

date1 & date1::operator+=(int addday)
{
  for(int i=0;i<addday;i++)
    {
       helpIncrement();
    }
  return *this;
}

ostream & operator<<(ostream & out,date1 & date)
{
   char * monthname[13]={" " , "January","February","Match","April","May",
   "June","July","August","September","October","November","December"};

   out<< date.day <<"/"<<monthname[date.month]<<" / " <<date.year<<endl;
   return out;
}
void main()
 {
    date1 d1,d(23,5,2006);
    cout<<d1;
    cout<<d;
    cout<<d++;
    cout<<d;
    d+=2;
    cout<<d;
    getch();
 }

Comments

Popular posts from this blog

Khoá luyện thi đại học đảm bảo 2012

10 chiêu tăng tuổi thọ cho pin laptop

Viết bài như thế nào để tốt cho SEO