/* Copyright (c) 2016
* All rights reserved
* 文件名称:3.cpp
* 作者:刘丽
* 完成日期:2016年 3 月 17日
* 版本号: v1.0
*
* 问题描述:一个关于时间的类(友元类),不计闰年
*/
#include <iostream>
#include<cmath>
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的友元类
Date(Date &d)
{
d.year=year;
d.month=month;
d.day=day;
}
private:
int month;
int day;
int year;
};
Time::Time(int hour,int minute,int sec):hour(hour),minute(minute),sec(sec)
{
}
void Time::add_a_second(Date &d)
{
sec++;
if(sec==60)
{
sec=0;
minute++;
if(minute==60)
{
minute=0;
hour++;
if(hour==24)
{
hour=0;
switch(d.month)
{
case 2:if(d.day==28)
{
d.day=1;
d.month++;break;
}
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:if(d.day==31)
{
d.day=1;
d.month++;
break;
}
case 12:if(d.day==31)
{
d.day=1;
d.year++;
d.month=1;
}break;
default:if(d.day==30)
{
d.day=1;
d.month++;
}
}
}
}
}
}
void Time::display(Date &d)
{
cout<<d.year<<"年 "<<d.month<<"月 "<<d.day<<"日 "<<hour<<":"<<minute<<":"<<sec<<endl;
}
Date::Date(int month,int day,int year):month(month),day(day),year(year)
{
}
int main( )
{
Time t1(23,59,32);
Date d1(2,28,2013); //测试时,再试试Date d1(2,28,2013)会如何
for(int i=0; i<=100; i++)
{
t1.add_a_second(d1);
t1.display(d1);
}
return 0;
}
<img src="https://img-blog.csdn.net/20160412195055450?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
一个关于时间的类(友元类),不计闰年
最新推荐文章于 2022-07-27 14:30:39 发布