(补)C++第6次实验(提高班)—类和对象2 项目3:友元类
一、问题和代码
作 者:杨振宇
完成日期:2017 年 5月 7日
版 本 号:v1.0
对任务及求解方法的描述部分:定义下面两个类的成员函数(为体验友元类,实际上本例并不一定是一个好的设计,)
输入描述:输入时分秒,月日年
问题描述:将两个类的合并为一个DateTime,日期、时间都处理更好
程序输出:输出月日年时分秒
问题分析:编辑两个类的成员函数,将时分秒,月日年合并显示
算法设计:在一个成员函数内对加一秒后的时间变化进行判断和输出,自定义一个函数对每年的月份天数进行判断
#include<iostream>
using namespace std;
int fun(int m,int y);
class Date;
class Time
{
public:
Time (int,int,int);
void add_a_second(Date &);
void display(Date &);
private:
int hour;
int minute;
int sec;
};
using namespace std;
int fun(int m,int y);
class Date;
class Time
{
public:
Time (int,int,int);
void add_a_second(Date &);
void display(Date &);
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend class Time;
private:
int month;
int day;
int year;
};
{
public:
Date(int,int,int);
friend class Time;
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
Date::Date(int m,int d,int y)
{
month=m;
day=d;
year=y;
}
void Time::add_a_second(Date &d)
{
sec++;
if(sec+1>=60)
{
minute+=1;
sec=sec+1-60;
}
if(minute>=60)
{
hour+=1;
minute=minute-60;
}
if(hour>=24)
{
d.day+=1;
hour=hour-24;
}
if(d.day>fun(d.month,d.year))
{
d.month+=1;
d.day=d.day-fun(d.month,d.year);
}
if(d.month>12)
{
d.year+=1;
d.month=d.month-12;
}
}
void Time::display(Date &d)
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<"/";
cout<<hour<<":"<<minute<<":"<<sec;
}
int fun(int m,int y)
{
int x;
switch(m)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:x=31;break;
case 4:
case 6:
case 9:
case 11:x=30;break;
case 2:
if(y%4==0)
{
x=29;
}
else
{
x=28;
};break;
}
return x;
}
return x;
}
int main()
{
Time t1(23,59,32);
Date d(12,31,2013);
for(int i=0;i<=80;i++)
{
t1.add_a_second(d);
t1.display(d);
}
return 0;
}
{
Time t1(23,59,32);
Date d(12,31,2013);
for(int i=0;i<=80;i++)
{
t1.add_a_second(d);
t1.display(d);
}
return 0;
}
二、运行结果