#include<iostream>
using namespace std;
class Date;
class Time
{
public:
Time(int a,int b,int c):hour(a),minute(b),sec(c) {};
void add_a_second(Date &); //增加1秒,1秒后可能会到了下一天,乃到下一月、下一年
void display(Date &); //显示时间,格式:月/日/年 时:分:秒
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int a,int b,int c):month(a),day(b),year(c) {};
friend class Time; //Time为Date的友元类
private:
int month;
int day;
int year;
};
int main( )
{
Time t1(23,59,32);
Date d1(2,28,2012); //测试时,再试试Date d1(2,28,2013)会如何
for(int i=0; i<=100; i++)
{
t1.add_a_second(d1);
t1.display(d1);
}
return 0;
}
void Time::display(Date&t)
{
cout<<t.year<<"/"<<t.month<<"/"<<t.day<<"/"<<hour<<":"<<minute<<":"<<sec<<endl;
}
void Time::add_a_second(Date&t)
{
sec++;
if(sec>=60)
{
sec=0;
minute++;
if(minute>=60)
{
minute=0;
hour++;
if(hour>=24)
{
hour=0;
t.day++;
switch(t.month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(t.day>31)
{
t.day=1;
t.month++;
}
break;
case 4:
case 6:
case 9:
case 11:
if(t.day>30)
{
t.day=1;
t.month++;
}
break;
case 2:
if(t.day>28)
if(t.year%4==0&&t.year%100!=0||t.year%400==0)
if(t.day>29)
{
t.day=1;
t.month++;
}
else;
else
{
t.day=1;
t.month++;
}
else
;
}
if(t.month>12)
{
t.month=1;
t.year++;
}
}
}
}
}
<img src="https://img-blog.csdn.net/20150415132009579?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2xpdXpoaWxpbw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="https://img-blog.csdn.net/20150415132238169?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2xpdXpoaWxpbw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />