类与对象——时间日期

类与对象——时间日期


这是我大一下时学校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;
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值