161-4

题目描述:设计一个日期类Date,数据成员包括年、月、日,定义其构造函数,且提供求取当前日期前一天的日期(即昨天)、当前日期后一天的日期(即明天)及显示日期(显示格式为:年/月/日)的成员函数,设分别为Yesterday( )、Tomorrow( )及Disp_Date( )。主函数创建一个日期类对象,其年、月、日的值由用户输入,程序显示当前用户输入的日期及其昨天和明天的日期。
 

头文件:Date.h

 

#ifndef _DATE_H_
#define _DATE_H_
class Date {
public:
	Date(int,int,int);
	void Yesterday();
	void Tomorrow();
	void Disp_Date();
	void Cheak();
private:
	int year, month, day;
	bool Is_Leap_Year();
};
#endif

 

类的实现:Date.cpp

 

#include "Date.h"
#include <iostream>
#include <stdlib.h>
Date::Date(int y, int m, int d) :year(y), month(m), day(d) { Cheak(); }
void Date::Yesterday() {
	Date d = *this;
	if (day == 1) {
		if (month == 1) {
			d.year--;
			d.month = 12;
			d.day = 31;
		}
		else if (month - 1 == 2) {
			if (Is_Leap_Year()) {
				d.month--;
				d.day = 29;
			}
			else {
				d.month--;
				d.day = 28;
			}
		}
		else if (month - 1 == 1 || month - 1 == 3 || month - 1 == 5 || month - 1 == 7 || month - 1 == 8 || month - 1 == 10) {
			d.month--;
			d.day = 31;
		}
		else {
			month--;
			day = 30;
		}
	}
	else d.day--;
	d.Disp_Date();
}
void Date::Tomorrow() {
	Date d = *this;
	if (day == 31) {
		if (month == 12) {
			d.year++;
			d.month = 1;
			d.day = 1;
		}
		else {
			d.month++;
			d.day = 1;
		}
	}
	else if (day == 30 && (month == 4 || month == 6 || month == 9 || month == 11)) {
		d.month++;
		d.day = 1;
	}
	else if (month == 2) {
		if (day == 29 || (day == 28 && !Is_Leap_Year())) {
			d.month++;
			d.day = 1;
		}
		else d.day++;
	}
	else d.day++;
	d.Disp_Date();
}
void Date::Disp_Date() {
	std::cout << year << '/' << month << '/' << day << std::endl;
}
void Date::Cheak() {
	try {
		if (month > 12 || month < 1) throw 0;
		if (day <= 0) throw 1;
		if (day > 31) throw 1;
		if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11 || month == 10)) throw 1;
		if (day > 29 && month == 2 && Is_Leap_Year()) throw 1;
		if (day > 28 && month == 2 && !Is_Leap_Year()) throw 1;
	}
	catch (int x) {
		if (x == 0) {
			std::cout << "月份错误,程序将退出。" << std::endl;
			exit(1);
		}
		if (x == 1) {
			std::cout << "日期错误,程序将退出。" << std::endl;
			exit(1);
		}
	}
}
bool Date::Is_Leap_Year() {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return true;
	else return false;
}

 

主程序:main.cpp

 

#include "Date.h"
#include <iostream>
int main() {
	int y, m, d;
	std::cin >> y >> m >> d;
	Date date(y, m, d);
	date.Disp_Date();
	date.Tomorrow();
	date.Yesterday();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值