友元函数 日期类 这个程序我读不懂,请问一下各位高手,这个程序该怎么理解??
1、 定义日期类Date包含年、月、日3个数据成员,编写一个友元函数,求两个日期之间相差的天数。#include<iostream.h>
#include<stdio.h>
class Date
{
int year;
int month;
int day;
public:
Date(int y,int m,int d)
{
year=y;month=m;day=d;
}
void disp()
{
cout<<year<<month<<day<<endl;
}
friend int count_day(Date &d,int);
friend int l(int year);
friend int h(Date &d1,Date &d2);
};
int count_day(Date &d,int k)
{
static int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}};
// 使用二维数组存放各月天数,第一行对应非闰年,第二行对应闰年
int j,i,s;
if(l(d.year))
j=1;
else j=0;
if(k)
{
s=d.day;
for(i=1;i<d.month;i++)
s+=day_tab[j][i-1];
}
else
{
s=day_tab[j][d.month]-d.day;
for(i=d.month+1; i<=12; i++)
s+=day_tab[j][i-1];
}
return s;
}
int l(int year)
{
if(year%4==0&&year%100!=0||year%400==0) // 是闰年
return 1;
else // 不是闰年
return 0;
}
int h(Date &d1,Date &d2)
{
int days,day1,day2,y;
if(d1.year<d2.year)
{
days=count_day(d1,0);
for(y=d1.year+1;y<d2.year;y++)
if(l(y))
days+=366L;
else
days+=365L;
days+=count_day(d2,1);
}
else if(d1.year==d2.year)
{
day1=count_day(d1,1);
day2=count_day(d2,1);
days=day2-day1;
}
else
days=-1;
return days;
}
void main()
{
Date d1(2000,1,1),d2(2002,10,1);
int ds=h(d1,d2);
{
cout<<"输出结果:"<<endl;
}
if(ds>=0)
{
d1.disp(); printf("与");
d2.disp(); printf("之间有%d天\n\n",ds);
}
else
cout<<"时间错误!"<<endl;
}