关于c++类的设计练习

仿照 Time 类的设计,设计一个 Date 类,数据成员为年、月和日,成员函数包括:

适当的构造函数和析构函数,其中的转换构造函数将从今年元旦(含元旦)以来的天

数(<366)转换为 Date 类对象;

设置年、月和日的函数;

读取年、月和日的函数;

重载流提取和流插入运算符函数;

重载前自增和后自增运算符函数;

重载转换运算符函数,将 Date 类对象转换为天数(该年的第几天)

代码如下,如有帮助,请采纳一下,谢谢。

#include <iostream>
#include <string>
using namespace std;
class Date
{
public:
	int year;
	int month;
	int day;
	Date(int y,int m,int d){year = y;month = m;day = d;}
	~Date(){}
	Date(long days)
	{
		int i;
		int ss = 0;
		int ds[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
		for (i = 0;ss < days;i++)
		{
			ss += ds[i];
		}
		year = 2021;
		month = i -1;
		day = day - (ss - ds[i]);
	}

	friend ostream & operator<<(ostream &o,const Date &s);
	friend istream & operator>>(istream &is,Date &s);
	
	Date& operator++()
	{
		day++;
		int ds[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
		switch(month)
		{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
			if(day > 31)
			{
				day = 1;
				month++;
			}
			break;
		case 2:
			if (year %4 == 0 && year %100 != 0 || year%400 == 0)
			{
				if(day > 29)
				{
					day = 1;
					month = 3;
				}
			}else
			{
				if(day > 28)
				{
					day = 1;
					month = 3;
				}
			}
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			if (day > 30)
			{
				day = 1;
				month++;
			}
			break;
		case 12:
			if (day > 31)
			{
				month = 1;
				year++;
				day = 1;
			}
			break;
		}
		return (*this);
	}
	Date operator++(int)
	{
		Date tmp = (*this);
		tmp.day++;
		int ds[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
		switch(tmp.month)
		{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
			if(tmp.day > 31)
			{
				tmp.day = 1;
				tmp.month++;
			}
			break;
		case 2:
			if (tmp.year %4 == 0 && tmp.year %100 != 0 || tmp.year%400 == 0)
			{
				if(tmp.day > 29)
				{
					tmp.day = 1;
					tmp.month = 3;
				}
			}else
			{
				if(tmp.day > 28)
				{
					tmp.day = 1;
					tmp.month = 3;
				}
			}
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			if (tmp.day > 30)
			{
				tmp.day = 1;
				tmp.month++;
			}
			break;
		case 12:
			if (tmp.day > 31)
			{
				tmp.month = 1;
				tmp.year++;
				tmp.day = 1;
			}
			break;
		}
		return Date(tmp);
	}

	operator int()
	{
		int i;
		int ss = 0;
		int ds[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
		for (i = 0;i <= month;i++)
		{
			ss += ds[i];
		}
		ss += day;
		return ss;
	}
};

ostream & operator<<(ostream &o,const Date &s)
{
	o << s.year << "-" << s.month << "-" << s.day;
	return o;
}
istream & operator>>(istream &is,Date &s)
{
	string inputStr;
	is >> inputStr;
	int pos = inputStr.find("-",0);
	string tmpStr = inputStr.substr(0,pos);
	s.year = atoi(tmpStr.c_str());
	int pos2 = inputStr.find("-",pos + 1);
	tmpStr = inputStr.substr(pos+1,pos2-pos -1);
	s.month = atoi(tmpStr.c_str());
	tmpStr = inputStr.substr(pos2+1,inputStr.length() - pos2 -1);
	s.day = atoi(tmpStr.c_str());
	return is;
}