- 设计一个日期类Date,包括年、月、日等私有数据成员。
要求:
- 实现日期的基本运算,如一日期加上天数、一日期减去天数、两日期相差的天数等。
- 要求:使用运算符重载。(为便于计算,我们假设每月的天数都是30天)
#include <iostream>
#include<algorithm>
using namespace std;
class Date
{
public:
Date()
{
d=0;
r=0;
y=0;
date=0;
}
Date(int d,int r,int y)
{
this->d=d;
this->r=r;
this->y=y;
}
Date(int da)
{
d=da;
y=0;
r=0;
}
friend Date operator+(Date c1,Date c2);
friend Date operator-(Date c1,Date c2);
friend Date operator-=(Date &c1,Date &c2);
void display()
{
cout<<y<<"年 "<<r<<"月 "<<d<<"日"<<endl;
}
void print()
{
cout<<date;
}
private:
int d;
int r;
int y;
int date;
};
Date operator+(Date c1,Date c2)
{
c1.d=c1.d+c2.d;
int x=c1.d/30;
c1.d=c1.d%30;
c1.r=c1.r+x;
int y=c1.r/12;
c1.r=c1.r%12;
c1.y=c1.y+y;
return c1;
}
Date operator-(Date c1,Date c2)
{
c1.d-=c2.d;
while(c1.d<0)
{
c1.r--;
c1.d=c1.d+30;
}
while(c1.r<0)
{
c1.y--;
c1.r=c1.r+12;
}
return c1;
}
Date operator-=(Date &c1,Date &c2)
{
int x1,x2;
x1=c1.r*30;
x2=c2.r*30;
int y1,y2;
y1=c1.y*360;
y2=c2.y*360;
int sum1,sum2;
sum1=c1.d+x1+y1;
sum2=c2.d+x2+y2;
c1.date=abs(sum1-sum2);
return c1;
}
int main()
{
Date c1(24,12,2019),c2(21,12,2019),c3,c4,c5;
cout<<"c1 = ";
c1.display();
cout<<"c2 = ";
c2.display();
cout<<"日期加上天数 : ";
c3=c1+11;
c3.display();
cout<<"日期减去天数 : ";
c4=c2-22;
c4.display();
cout<<"两日期相差的天数 : ";
c1-=c2;
c1.print();
return 0;
}
结果: