//date.h
#ifndef DATE_H
#define DATE_H
class Date {
public:
Date(); // 默认构造函数,将日期初始化为1970年1月1日
Date(int y, int m, int d); // 带有形参的构造函数,用形参y,m,d初始化年、月、日
void display(); // 显示日期
int getYear() const; // 返回日期中的年份
int getMonth() const; // 返回日期中的月份
int getDay() const; // 返回日期中的日字
int dayOfYear(); // 返回这是一年中的第多少天
private:
int year;
int month;
int day;
};
#endif
//date.cpp
#include "date.h"
#include "utils.h"
#include <iostream>
using std::cout;
using std::endl;
// 补足程序,实现Date类中定义的成员函数
Date::Date():year(1970),month(1),day(1){}// 默认构造函数,将日期初始化为1970年1月1日
Date::Date(int y, int m, int d):year(y),month(m),day(d){} // 带有形参的构造函数,用形参y,m,d初始化年、月、日
void Date::display()// 显示日期
{
cout<<year<<","<<month<<","<<day<<endl;
}
int Date::getYear() const // 返回日期中的年份
{
return year;
}
int Date::getMonth() const // 返回日期中的月份
{
return month;
}
int Date::getDay() const// 返回日期中的日字
{
return day;
}
int Date::dayOfYear() // 返回这是一年中的第多少天
{
int a=31,b,c=30,num;
bool m=isLeap(year);
if (m)
b=29;
else
b=28;
switch(month)
{
case 1:num=day;break;
case 2:num=a+day;break;
case 3:num=a+b+day;break;
case 4:num=2*a+b+day;break;
case 5:num=2*a+b+c+day;break;
case 6:num=3*a+b+c+day;break;
case 7:num=3*a+b+2*c+day;break;
case 8:num=4*a+b+3*c+day;break;
case 9:num=5*a+b+2*c+day;break;
case 10:num=5*a+b+3*c+day;break;
case 11:num=6*a+b+3*c+day;break;
case 12:num=6*a+b+4*c+day;break;
}
return num;
}
//utils.h
// 工具包头文件,用于存放函数声明
// 函数声明
bool isLeap(int);
//utils.cpp
// 功能描述:
// 判断year是否是闰年, 如果是,返回true; 否则,返回false
bool isLeap(int year) {
if( (year % 4 == 0 && year % 100 !=0) || (year % 400 == 0) )
return true;
else
return false;
}