C++.Experiment 4.Operator overloading(& date plus days)

/*设计一个日期类Date,,要求:
(1)包含年(year)、月(month)和日(day)私有数据成员。
(2)包含构造函数,
重载关于一日期加上天数的加法运算符+、
重载关于一日期减去天数的减加运算符-、
重载输出运算符<<与输入运算符>>等。
*/
#include<iostream>
using namespace std;
class Date{
private:
	int year,month,day;
public:
	Date(int y=2013,int m=1,int d=1):year(y),month(m),day(d){};
	friend Date &operator+(Date&,int);
	friend Date &operator-(Date&,int);
	friend ostream&operator<<(ostream &os,Date &D){os<<D.year<<"/"<<D.month<<"/"<<D.day;return os;};
	friend void operator>>(istream &is,Date &D){is>>D.year>>D.month>>D.day;};
};
Date &operator+(Date &D,int d){
	switch(D.month){
	case 1:case 3:case 5:case 7:case 8:case 10:case 12:
		if(D.day+d>31){
			D.month++;
			d=d-(31-D.day)-1;
			D.day=1;
			if(D.month==13){
				D.year++;
				D.month=1;
			}
			D+d;
		}else{
			D.day+=d;
		}break;
	case 2:
		if((D.year%100!=0&&D.year%4==0)||(D.year%400==0)){
			if((D.day+d)>29){
				D.month++;
				d=d-(29-D.day)-1;
				D.day=1;
				D+d;
			}else{
				D.day+=d;
			}break;
		}else{
			if((D.day+d)>28){
				D.month++;
				d=d-(28-D.day)-1;
				D.day=1;
				D+d;
			}else{
				D.day+=d;
			}break;
		}
	default:
		if((D.day+d)>30){
			D.month++;
			d=d-(30-D.day)-1;
			D.day=1;
			D+d;
		}else{
			D.day+=d;
		}break;
	}
	return D;
}
Date &operator-(Date &D,int d){
	switch(D.month){
	case 1:case 2:case 4:case 6:case 8:case 9:case 11:
		if(D.day-d<0){
			D.month--;
			d=d-D.day;
			D.day=31;
			if(D.month==0){
				D.year--;
				D.month=12;
			}
			D-d;
		}else{
			D.day-=d;
		}break;
	case 3:
		if((D.year%100!=0&&D.year%4==0)||(D.year%400==0)){
			if(D.day-d<0){
				D.month--;
				d=d-D.day;
				D.day=29;
				D-d;
			}else{
				D.day-=d;
			}break;
		}else{
			if(D.day-d<0){
				D.month--;
				d=d-D.day;
				D.day=28;
				D-d;
			}else{
				D.day-=d;
			}break;
		}
	default:
		if(D.day-d<0){
			D.month--;
			d=d-D.day;
			D.day=30;
			D-d;
		}else{
			D.day-=d;
		}break;
	}
	return D;
}

void main(){
	Date D;
	cin>>D; //输入日期
	cout<<D<<endl;//输出日期
	cout<<D+1000<<endl;
	cout<<D-1000<<endl;
	system("PAUSE");
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值