/*。
*Copyright(c)2014,烟台大学计算机学院
*All right reserved,
*文件名:test.cpp
*作者:毕玉堂
*完成日期:2015年4月17日
*版本号:v1.0
*
问题描述:
*输入描述:
*程序输出:
*/
#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time
{
public:
Time(int,int,int);
void add_a_second(Date &); //增加1秒,1秒后可能会到了下一天,乃到下一月、下一年
void display(Date &); //显示时间,格式:月/日/年 时:分:秒
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend class Time; //Time为Date的友元类
private:
int month;
int day;
int year;
};
int main( )
{
Time t1(23,59,55);
Date d1(12,31,2013); //测试时,再试试Date d1(2,28,2013)会如何
for(int i=0; i<=5; i++)
{
t1.add_a_second(d1);
t1.display(d1);
}
return 0;
}
Time::Time(int x,int y,int z)
{
hour=x;
minute=y;
sec=z;
}
Date::Date(int m,int n ,int r)
{
month=m;
day=n;
year=r;
}
void Time::add_a_second(Date &d)
{
sec+=1;
if(sec>59)
{
sec=0;
minute+=1;
}
if(minute>59)
{
minute=0;
hour+=1;
}
if(hour>23)
{
hour=0;
d.day+=1;
}
if(d.month==1||d.month==3||d.month==5||d.month==7||d.month==8||d.month==10||d.month==12)
{
if(d.day>31)
{
d.day=1;
d.month+=1;
}
}
if(d.month==4||d.month==6||d.month==9||d.month==11)
{
if(d.day>30)
{
d.day=1;
d.month+=1;
}
}
if((d.year%4==0&&d.year%100!=0)||d.year%400==0)
{
if(d.month==2)
{
if(d.day>29)
{
d.day=1;
d.month+=1;
}
}
}
else
{
if(d.month==2)
{
if(d.day>28)
{
d.day=1;
d.month+=1;
}
}
}
if(d.month>12)
{
d.month=1;
d.year+=1;
}
}
void Time::display(Date &d)
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<" "<<hour<<":"<<minute<<":"<<sec<<endl;
}
运行结果: