第一题1. 补足日期类实现,使得能够根据日期获取这是一年中第多少天。(12分)
date.h
1 #ifndef DATE_H 2 #define DATE_H 3 4 class Date { 5 public: 6 Date(); // 默认构造函数,将日期初始化为1970年1月1日 7 Date(int y, int m, int d); // 带有形参的构造函数,用形参y,m,d初始化年、月、日 8 void display(); // 显示日期 9 int getYear() const; // 返回日期中的年份 10 int getMonth() const; // 返回日期中的月份 11 int getDay() const; // 返回日期中的日字 12 int dayOfYear(); // 返回这是一年中的第多少天 13 14 private: 15 int year; 16 int month; 17 int day; 18 }; 19 20 #endif
utils.h
1 // 工具包头文件,用于存放函数声明 2 3 // 函数声明 4 bool isLeap(int);
date.cpp
1 #include "date.h" 2 #include "utils.h" 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 /* 8 class Date { 9 public: 10 Date(); // 默认构造函数,将日期初始化为1970年1月1日 11 Date(int y, int m, int d); // 带有形参的构造函数,用形参y,m,d初始化年、月、日 12 void display(); // 显示日期 13 int getYear() const; // 返回日期中的年份 14 int getMonth() const; // 返回日期中的月份 15 int getDay() const; // 返回日期中的日字 16 int dayOfYear(); // 返回这是一年中的第多少天 17 18 private: 19 int year; 20 int month; 21 int day; */ 22 // 补足程序,实现Date类中定义的成员函数 23 Date::Date ():year(1970),month(1),day(1) 24 { 25 } 26 Date::Date(int y,int m,int d):year(y),month(m),day(d) 27 { 28 29 } 30 void Date::display() 31 { 32 cout<<year<<'-'<<month<<'-'<<day<<endl; 33 } 34 int Date::getDay()const 35 { 36 return day; 37 } 38 int Date::getMonth()const 39 { 40 return month; 41 } 42 int Date::getYear()const 43 { 44 return year; 45 } 46 int Date::dayOfYear() 47 { 48 int sum=0; 49 int month1[12]={31,28,31,30,31,30,31,31,30,31,30,31}; 50 if(isLeap(year)) 51 month1[1]=29; 52 for(int i=0;i<month-1;i++) 53 sum+=month1[i]; 54 sum+=day; 55 return sum; 56 }
main.cpp
1 #include "utils.h" 2 #include "date.h" 3 4 #include <iostream> 5 using namespace std; 6 int main() { 7 8 Date epochDate; 9 epochDate.display(); 10 cout << "是" <<epochDate.getYear()<<"年第"<< epochDate.dayOfYear() << "天.\n\n" ; 11 12 Date today(2019,4,30); 13 14 today.display(); 15 cout << "是" <<today.getYear()<<"年第"<< today.dayOfYear() << "天.\n\n" ; 16 17 Date tomorrow(2019,5,1); 18 tomorrow.display(); 19 cout << "是" <<tomorrow.getYear()<<"年第"<< tomorrow.dayOfYear() << "天.\n\n"; 20 21 system("pause"); 22 return 0; 23 }
utils.cpp
1 // 功能描述: 2 // 判断year是否是闰年, 如果是,返回true; 否则,返回false 3 4 bool isLeap(int year) { 5 if( (year % 4 == 0 && year % 100 !=0) || (year % 400 == 0) ) 6 return true; 7 else 8 return false; 9 }