定义日期类Date,并重载运算符实现几种操作

题目要求这样:定义一日期Date类,重载++,--,-和^ 运算,分别完成求日期+1,-1, 两个日期相减之间天数,以及取对应日期的星期几的操作,并编写主函数进行测试。

代码:

Date类

//
//  Date.h
//  Date
//
//  Created by KevinLee on 15/10/13.
//  Copyright © 2015年 KevinLee. All rights reserved.
//

#include 
#include 
using namespace std;
static int dom1[12]={31,28,31,30,31,30,31,31,30,31,30,31};//Day of Month 平年
static int dom2[12]={31,29,31,30,31,30,31,31,30,31,30,31};//Day of Month 闰年
bool isLeap(int year){//判断是否是闰年
    return (year%4==0&&year%100!=0)||year%400==0?true:false;
}
class Date{
private:
    int year,month,day;
public:
    Date(int y,int m,int d){
        year=y;month=m;day=d;
        cout<<"New Date:["<12) {
            cout<<"Wrong month!"<dom2[month-1])||day<1||(isLeap(year)==false&&day>dom1[month-1])){
            cout<<"Wrong day!"<12) {
                year++;
                month=1;
            }
        }
        else{
            day++;
        }
    }
    else{
        if (day==dom1[month-1]) {
            day=1;
            month++;
            if (month>12) {
                year++;
                month=1;
            }
        }
        else{
            day++;
        }
    }
    return *this;
}
Date Date::operator--(int i){
    if (isLeap(year)) {
        if (day==1) {
            month--;
            if (month<1) {
                year--;
                month=12;
            }
            day=dom2[month-1];
        }
        else{
            day--;
        }
    }
    else{
        if (day==1) {
            month--;
            if (month<1) {
                year--;
                month=12;
            }
            day=dom1[month-1];
        }
        else{
            day--;
        }
    }
    return *this;
}

int Date::operator-(Date other){//利用成员函数重载
    int subDay=0;
    if(this->year==other.year){
        subDay+=abs(this->countDays()-other.countDays());
    }
    else{
        if(this->yearyear-other.year>2){
            for(int i=1;iyear-other.year;i++){
                subDay+=365;
                if(isLeap(other.year+i)){
                    subDay+=1;
                }
            }
        }
        subDay+=365-other.countDays()+this->countDays();
        if(isLeap(other.year)) subDay++;
    }
    return subDay;
}
string Date::operator^(int i){
    string str[7]={"Mon","Tue","Wed","Thur","Fri","Sat","Sun"};
    Date date("19000101");//已知1900年1月1日为星期一
    int flag;
    int day=*this-date+i;
    flag=day%7;
    return str[flag];
}

测试主函数:

//
//  main.cpp
//  Date
//
//  Created by KevinLee on 15/10/13.
//  Copyright © 2015年 KevinLee. All rights reserved.
//

#include 
#include "Date.h"
using namespace std;
int main(int argc, const char * argv[]) {
    Date date(2012,2,29),date2(2013,3,1),date3(2015,10,14);
    (date++).show();
    (date--).show();
    date.show();
    date2.show();
    date3.show();
    cout<




你可能感兴趣的:(c++)