2015-第6週プロジェクト5-友元類

1688 ワード

【項目5-友元類】
次の2つのクラスのメンバー関数を定義します(メタクラスを体験するために、実際にはこの例は必ずしも良い設計ではありません.2つのクラスを1つのDateTimeに統合し、日付、時間をよりよく処理します).
コード:
#include <iostream>
#include <cstring>
using namespace std;
int day(int m,int y)
{
    int d[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
    if((y%100==0&&y%4!=0)||(y%400==0))
        d[2]++;
    return d[m];
}
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;
};
Time::Time(int h,int m,int s)
{
    minute=m;
    hour=h;
    sec=s;
}
Date::Date(int m,int d,int y)
{
    month=m;
    day=d;
    year=y;
}
void Time::add_a_second(Date &b)
{
    sec++;
    if(sec>=60)
        minute++,sec-=60;
    if(minute>=60)
        hour++,minute-=60;
    if(hour>=24)
        b.day++,hour-=24;
    if(b.day>day(b.month,b.year))
        b.month++,b.day=1;
    if(b.month > 12)
        b.year++,b.month-=12;
}
void Time::display(Date &b)
{
    cout<<b.year<<" "<<b.month<<" "<<b.day<<" ";
    cout<<hour<<":"<<minute<<":"<<sec<<endl;
}

int main( )
{
    Time t1(23,59,32);
    Date d1(12,31,2013);   //   ,   Date d1(2,28,2013)   
    for(int i=0; i<=100; i++)
    {
        t1.add_a_second(d1);
        t1.display(d1);
    }
    return 0;
}

実行結果: