2016/5/27 1002. Modify Date class

首先按要求把Date类完善,在重载 [ ] 符号的时候注意把特殊情况给throw出去。

然后再自己写一个类IllegalSubscriptException(名字真长...),在类里写好what的就可以了。

#include <iostream>
using namespace std;
class IllegalSubscriptException
{
public:
	IllegalSubscriptException()
	{

	}
}a;
class Date
{
public:
	Date(int y = 0, int m = 1, int d = 1)
	{
		year_ = y;
		month_ = m;
		day_ = d;
	}
	static bool leapyear(int year)
	{
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}
	int getYear() const
	{
		return year_;
	}
	int getMonth() const
	{
		return month_;
	}
	int getDay() const
	{
		return day_;
	}
	bool operator<(Date &d)
	{
		if (year_ < d.year_)
		{
			return true;
		}
		else if (year_ == d.year_&&month_ < d.month_)
		{
			return true;
		}
		else if (year_ == d.year_&&month_ == d.month_&& day_ < d.day_)
		{
			return true;
		}
		else return false;
	}
	bool operator<=(Date &d)
	{
		if ((*this) < d|| (*this) == d)
		{
			return true;
		}
	}
	bool operator==(Date &d)
	{
		if (year_ == d.year_&&month_ == d.month_&& day_ == d.day_)
		{
			return true;
		}
		else return false;
	}
	bool operator!=(Date &d)
	{
		return !((*this == d));
	}
	bool operator>(Date &d)
	{
		return !((*this <= d));
	}
	bool operator>=(Date &d)
	{
		return !((*this < d));
	}
	int &operator[](const string &s)
	{
		if (s == "year")
		{
			return year_;
		}
		else if (s == "month")
		{
			return month_;
		}
		else if (s == "day")
		{
			return day_;
		}
		else
		{ 
			throw a;
		}
	}

	// add any member you need here
private:
	int year_, month_, day_;
};
//以上是要提交的部分
void f()
{
	Date date1(2011, 4, 1);
	try
	{
		cout << date1["abc"] << endl;
	}
	catch (IllegalSubscriptException ex)
	{
		cout << "Illegal Subscript Exception" << endl;
	}

	try
	{
		date1["abc"] = 2000;
	}
	catch (IllegalSubscriptException ex)
	{
		cout << "Illegal Subscript Exception" << endl;
	}
}
/*
What to do if the subscript is not one of "year", "month" or "day"?  
Define a custom exception class named IllegalSubscriptException and let the function operator [] 
throw an IllegalSubscriptException if the subscript is not one of "year", "month" or "day".
*/
int main()
{
	Date date(2011, 4, 1);
	cout << date["year"] << endl; // output 2011
	cout << date["month"] << endl;// output 4
	cout << date["day"] << endl; // output 1
	date["year"] = 2007;
	date["month"] = 11;
	date["day"] = 11;
	cout << date["year"] << endl; // output 2007
	cout << date["month"] << endl;// output 11
	cout << date["day"] << endl; // output 11
	f();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值