问题及代码
ALL rights reserved.
*文件名称: 初学对象6
作者:李长鸿
*完成时间:2015.4.15
*问题描述: 阅读程序
*/
#include<iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time
{
public:
Time(int h,int m,int s):hour(h),minute(m),sec(s) {}
void add_a_second(Date &H); //增加1秒,1秒后可能会到了下一天,乃到下一月、下一年
void display(Date &H)
{
cout<<H.month<<'//'<<H.day<<'//'<<H.year<<" "<<hour":"<<minute<<":"<<sec<<endl;
} //显示时间,格式:月/日/年 时:分:秒
private:
int hour;
int minute;
int sec;
};
void Time::add_a_second(Date &H)
{
int r=31;
if(H.month==2)
{
if((H.year%4==0&&H.year%100==0)||(H.year%400==0))r=28;
else r=29;
}
else if(H.month==4||H.month==6||H.month==9||H.month==11)r=30;
sec=sec+1;
if(sec==60)
{
sec=0;
minute=minute+1;
}
if(minute==60)
{
minute=0;
hour=hour+1;
}
if(hour==24)
{
hour=0;
H.day=H.day+1;
}
if(H.day=r)
{
H.day=1;
H.month=H.month+1;
}
if(H.month=12)
{
H.month=1;
H.year=H.year+1;
}
}
class Date
{
public:
Date(int m,int d,int y):month(m),day(d),year(y) {}
friend class Time; //Time为Date的友元类
int month;
int day;
int year;
};
int main( )
{
Time t1(23,59,32);
Date d1(12,31,2013); //测试时,再试试Date d1(2,28,2013)会如何
for(int i=0; i<=100; i++)
{
t1.add_a_second(d1);
t1.display(d1);
}
return 0;
}