第6周项目5友元类

/*。
*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;
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值