关闭

c++日期类

1569人阅读 评论(0) 收藏 举报

包含年月日


头文件:

#include"iostream"
using namespace std;
#ifndef _DATE_H	
#define _DATE_H

class Date{
public:
	Date();
	Date( int _year, int _month, int _day );        
	

	int getYear();
	int getMonth();
	int getDay();
	
	void setYear(int year);
	void setMonth(int month);
	void setDay(int day);
	
	bool is_run_nian();
	int get_maxday();
	void inc();
	//运算符重载 
	friend ostream & operator<<(ostream & out, const Date & a);
	Date operator++(int);
	void addOneDay();
	void print();
private:
	int year;
	int month;
	int day;

};
#endif

cpp文件

#include"Date.h"

Date::Date(){
	
}
Date::Date( int _year, int _month, int _day ){
	year = _year;
	month =_month;
	day=_day;
	
}

int Date::getYear(){
	return year;
}
int Date::getMonth(){
	return month;
}
int Date::getDay(){
	return day;
}


void Date::setYear(int year){
	year=year;
}
void Date::setMonth(int month){
	month=month;
}
void Date::setDay(int day){
	day=day;
}
void Date::print(){
	cout<<"year:"<<Date::year<<endl;
	cout<<"month:"<<Date::month<<endl;
	cout<<"day:"<<Date::day<<endl; 
}
//运算符重载 
ostream & operator<<(ostream& out, const Date& a){
    out<<"("<<a.year<<"-"<<a.month<<"-"<<a.day<<")"<<endl;
    return out;
}

//运算符重载 
Date Date::operator++(int){
	Date tmp(this->year,this->month,this->day);
    addOneDay();
    return tmp;
}
//判断日期 
void Date::addOneDay(){
	switch(month)
		{
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
				{
					if(day<=30){
						day++;	
					}else if(day>31&&day<0){
						cout<<"请输入正确的日期"<<endl;
					}else
					{
						month++;
						day=1;
					}
					break;
				}
			case 12:
				{
					if(day<=30){
						
					
						day++;
					}else if(day>31&&day<0){
						cout<<"请输入正确的日期"<<endl;
					}
					else
					{
						year++;
						month=1;
						day=1;
					}
					break;
				}
			case 4:
			case 6:
			case 9:
			case 11:
				{
					if(day<=29){
						
						day++;
					}else if(day>30&&day<0){
							cout<<"请输入正确的日期"<<endl;
					}else
					{
						month++;
						day=1;
					}
					
					break;
				}
			case 2:
				{
					//判断是否是润年 
					int IsLeapYear=(year%4==0&&year%100!=0)||(year%400==0);
					if(IsLeapYear)
					{
						if(day<=28){
							
						
							day++;
						}else if(day>29&&day<0){
						cout<<"请输入正确的日期"<<endl;
					}else
						{
							month++;
							day=1;
						}
					}
					else
					{
						if(day<=27){
							
						
							day++;
						}else if(day>28){
						cout<<"请输入正确的日期"<<endl;
					}else
						{
							month++;
							day=1;
						}
					}
					break;
				}
			default:
				cout<<"请输入正确的月"<<endl; 
				break;
		}
		
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:450684次
    • 积分:6061
    • 等级:
    • 排名:第4295名
    • 原创:153篇
    • 转载:89篇
    • 译文:0篇
    • 评论:69条
    文章分类
    个人信息
    邮箱:xiaoyang_ios@sina.com
    最新评论