/*
* Copyright (c) 2011, 烟台大学计算机学院
* All rights reserved.
* 作 者:王静
* 完成日期:2013 年 4 月 16 日
* 版 本 号:v1.0
* 输入描述:
* 问题描述:定义下面两个类的成员函数(为体验友元类,实际上本例并
不一定是
一个好的设计,将两个类的合并为一个DateTime,日期、时间都处理更
好)
* 程序输出:
* 问题分析:
* 算法设计:略
*/
#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time
{
public:
Time(int a=0,int b=0,int c=0):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=0,int b=0,int c=0):day(c),month(b),year(a){};
friend class Time; //Time为Date的友元类
private:
int month;
int day;
int year;
};
//下面定义两个类中的成员函数,要求不得再增加成员函数
//注意体会在Time的成员函数中可以调用Date类的私有数据成员
void Time::add_a_second(Date &t)
{
int s,m,h,days;
switch(t.month){
case 1:
case 3:
case 5:
case 7:
case 9:
case 11:
days=31;break;
case 2:
if(t.year%4==0&&t.year%400!=0){
days=28;
}else{
days=29;
}
break;
case 4:
case 6:
case 8:
case 10:
case 12:
days=30;break;
}
sec=sec+1;
if(sec>60){
sec=sec-60;
minute=minute+1;
if(minute>60){
minute=minute-60;
hour=hour+1;
if(hour>24){
hour=hour-24;
t.day+=1;
if(t.day>days){
t.day=t.day-days;
t.month+=1;
if(t.month>12){
t.month=t.month-12;
t.year+=1;}
}
}
}
}
}
void Time::display(Date &t)
{
cout<<"年月日,时分秒为:"<<endl;
cout<<t.year<<"."<<t.month<<"."<<t.day<<"."<<hour<<":"<<minute<<
":"<<sec<<endl;
}
int main( )
{
Time t1=Time(24,60,60);
Date d1=Date(2012,12,30);
t1.display(d1);
t1.add_a_second(d1);
t1.display(d1);
return 0;
}
运行结果:(贴图)
心得体会: