/*
* 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;
}
運行結果:(貼圖)
心得體會: