类与对象——时间日期
这是我大一下时学校C++上机课的实验,题目不算特别难,主要是一些细节的考虑。
下面就是题目的要求:
1.定义一个满足如下要求的类Cdate:
(1)有三个成员数据:年、月、日;
(2)有设置日期的成员函数;
(3)有用格式“月/日/年”输出日期的成员函数;
有对当前日期加一天的成员函数。
#include <iostream>
using namespace std;
class Date {
public:
void SetDate(int y, int m, int d); //设置日期,传递参数和初始化
bool isLeapYear(int m_nYear); //判断是否为闰年
int Getmonthday(int m_nMonth, int m_nYear); //得到每个月有多少天
void display(); //输出函数
Date operator ++(); //重载++,对当天日期加1
private:
int m_nYear;
int m_nMonth;
int m_nDay;
};
void Date::SetDate(int y, int m, int d) {
if (m <= 12 && m >= 1) {
if (d >= 1 && d <= Getmonthday(m, y)) { //输入合理的月份和天数
m_nYear = y;
m_nMonth = m;
m_nDay = d;
}
else {
cout << "error" << endl;
m_nYear = 0; //当输入不合理时,时参数全为0
m_nMonth = 0;
m_nDay = 0;
}
}
else {
cout << "error" << endl;
m_nYear = 0;
m_nMonth = 0;
m_nDay = 0;
}
}
//判断是否为闰年
bool Date::isLeapYear(int m_nYear) {
if ((m_nYear % 4 == 0 && m_nYear % 100 == 0) || (m_nYear % 400 == 0))
return true;
else
return false;
}
//得到每个月的天数(这一步可以再弄简单点的,可以不需要这么长的)
int Date::Getmonthday(int m, int y) {
int x;
switch (m) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
x = 31;
break;
case 4:
case 6:
case 9:
case 11:
x = 30;
break;
case 2:
if (isLeapYear(y)) //每年的2月份天数都比较特殊,这也是需要判断闰年的原因
x = 29;
else
x = 28;
break;
default:
x = 0;
cout << "error" << endl;
break;
}
return x;
}
void Date::display() {
cout << m_nYear << "/" << m_nMonth << "/" << m_nDay << endl;
}
//在该日期上加一天
Date Date::operator ++() {
if (m_nDay == Getmonthday(m_nMonth, m_nYear)) { //当天数为该月的最后一天时
if (m_nMonth == 12) { //当月份为12时
m_nYear++;
m_nMonth = 1;
}
else {
m_nMonth++; //天数为最后一天,月份不为12月时
}
m_nDay = 1; //当天数不是该月最后一天时
}
else
++m_nDay;
return *this;
}
//主函数
int main() {
Date D;
int y, m, d;
cin >> y >> m >> d;
D.SetDate(y, m, d);
D.display();
++D;
D.display();
system("pause");
return 0;
}