getch();
return0;
}
结果截图:
4.设计一个日期类Date,,要求:
(1)包含年(year)、月(month)和日(day)私有数据成员。
(2)包含构造函数,重载关于一日期加上天数的加法运算符+、重载关于一日期减去天数的减加运算符-、重载输出运算符<<与输入运算符>>等。
提示:
由于各C++编译器对于重载输入/出运算符为友元的兼容性都存在问题,最好重载输入/出运算符不声明为成员函数与友元函数,而声明一般函数,为编程更方便,可增加一些成员函数,比如:
voidSetYear(inty);//设置年
intSetMonth(intm);//设置月
intSetDay(intd);//设置日
intGetYear()const;//返回年
intGetMonth()const;//返回月
intGetDay()const;//返回日
staticintIsLeapyear(inty);//判断年份y是否为润年
staticintGetDays(inty);//年份y的天数
staticintGetDays(constDate&d);//日期d当前月份的天数
staticintDateToNum(constDate&d);//返回从公元1年1月1日起的天数
staticDateNumToDate(intn);//由从公元1年1月1日起的天数返回日期
润年条件:
年份能被4整除,并且年份不能被100整除,或者年份能被400整除
润年天数:
366
平年天数:
365
润年2月份天数:
29
平年2月份天数:
28
(1)程序实现
#include"iostream.h"
#include
classDate
{
public:
Date(inta=0,intb=0,intc=0);
voidSet_Date(inta,intb,intc);
voidGet_Date();
Dateoperator+(int);
Dateoperator-(int);
friendostream&operator<<(ostream&,Date&);
friendistream&operator>>(istream&,Date&);
private:
intyear,mounth,date,m;
};
Date:
:
Date(inta,intb,intc)
{
year=a;
mounth=b;
date=c;
m=1;
}
voidDate:
:
Set_Date(inta,intb,intc)
{
year=a;
mounth=b;
date=c;
}
voidDate:
:
Get_Date()
{
if(m==1)
cout<else
cout<<"刚才输入的天数不符合要求!
"<}
DateDate:
:
operator+(inta)
{
if(a>28)
{
m=0;
return*this;
}
else
{
if((year%400==0)||((year%4==0)&&(year%100!
=0)))
{
if((mounth==4)||(