3. 设计一个日期类Date,包括年、月、日等私有数据成员。要求实现日期的基本运算,如一日期加上天数、一日期减去天数、两日期相差的天数等。要求:使用运算符重载。
#include<iostream>
using namespace std;
class Date
{
public:
Date(int y, int m, int d)
{
year = y;
mouth = m;
day = d;
}
void InputDate()
{
cin >> year >> mouth >> day;
}
Date operator+(Date &c);
Date operator-(Date &c);
int operator&(Date &c2);
void display();
~Date(){}
private:
int year;
int mouth;
int day;
};
Date Date::operator+(Date &c)
{
Date d(0, 0, 0);
d.day = day + c.day;
d.year = year;
d.mouth = mouth;
if(d.day > 30)
{
d.mouth = mouth + 1;
d.day = 1;
}
if(d.mouth > 12)
{
d.year = year + 1;
d.mouth = 1;
}
return d;
}
Date Date::operator-(Date &c)
{
Date d(0, 0, 0);
d.day = day - c.day;
d.year = year;
d.mouth = mouth;
if(d.day < 0)
{
d.day = 30;
d.mouth = mouth - 1;
}
if(d.mouth < 0)
{
d.mouth = 1;
d.year = year - 1;
}
return d;
}
int Date::operator&(Date &c2)
{
Date c(0, 0, 0);
int x = 0;
if(day > c2.day)
{
c.day = day - c2.day;
}
if(day < c2.day)
{
c.day = c2.day - day;
}
if(mouth > c2.mouth)
{
c.mouth = mouth - c2.mouth;
}
if(mouth < c2.mouth)
{
c.mouth = c2.mouth - mouth;
}
if(year > c2.year)
{
c.year = year - c2.year;
}
if(year < c2.year)
{
c.year = c2.year - year;
}
x = c.day + c.mouth * 30 + c.year * 365;
return x;
}
void Date::display()
{
if(year != 0 && mouth != 0)
{
cout << year << "年" << mouth << "月" << day << "日" << endl;
}
else
{
cout << day << "天" << endl;
}
}
int main(void)
{
Date c1(0, 0, 0), c2(0, 0, 0), c3(0,0,4), c4(0,0,1);
cout << "输入日期的格式年 月 日" << endl;
cout << "Please input the first Date:";
c1.InputDate();
cout << "Please input the second Date:";
c2.InputDate();
cout << "输入加减天数的格式0 0 天数" << endl;
cout << "Please input the add num:";
c3.InputDate();
Date c(0, 0, 0);
c = c1 + c3;
cout << "c1 + day =" << endl;
c.display();
cout << "Please input the sub num:";
c4.InputDate();
c = c1 - c4;
cout << "c1 - day = " << endl;
c.display();
int m = 0;
m = c1 & c2;
cout << endl << endl <<"第一个日期为:" << endl;
c1.display();
cout << "第二个日期为:" << endl;
c2.display();
cout << endl << "c1 - c2的天数为:" << m << endl;
return 0;
}