首先按要求把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();
}