Date Class with Exception
| ||
题目描述
As we have learnt before, we can use the subscript [] in the class Date to access the year, month, day of a Date object.
class Date
{
private:
int year;
MONTH month;
int day;
public:
Date(int y, MONTH m, int d);
int operator[] (const char *s);
};
Here, MONTH is an enum type which consists of a set of names: {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}.
You implementation should enable the usage like this:
Date date(2011,APR,1);
cout << date["year"] << endl; // output 2011
cout << date["month"] << endl;// output 4
cout << date["day"] << endl; // output 1
But what if the subscript is not "year", "month" or "day"?
Please design a custom exception class named IllegalSubscriptException and let the function operator [] throw an IllegalSubscriptException object if the subscript is not "year", "month" or "day".
The test framework is as follows.
int main()
{
Date date1(2011, APR, 1);
try {
cout << date1["year"] << endl;
} catch (IllegalSubscriptException ex) {
cout << ex.what() << endl;
}
try {
cout << date1["month"] << endl;
} catch (IllegalSubscriptException ex) {
cout << ex.what() << endl;
}
try {
cout << date1["day"] << endl;
} catch (IllegalSubscriptException ex) {
cout << ex.what() << endl;
}
try {
cout << date1["abc"] << endl;
} catch (IllegalSubscriptException ex) {
cout << ex.what() << endl;
}
return 0;
}
Then the output should be:
2011
4
1
Illegal Subscript Exception
提示
You don't need to worry about the setting of year, month and day in the Date constructor.
Please submit the definition and implementation of classes IllegalSubscriptException and Date.
Please also submit the definition of the enum MONTH.
You don’t need to submit the main() function. | ||
|
class IllegalSubscriptException
{
public :
IllegalSubscriptException(const char *s)
{
meg = new char [1000] ;
meg = s ;
}
const char * what()
{
return meg ;
}
private :
const char *meg ;
};
class Date
{
private:
int year;
MONTH month;
int day;
public:
Date(int y, MONTH m, int d);
int operator[] (const char *s);
};
Date::Date(int y , MONTH m , int d)
{
year = y ;
month = m ;
day = d ;
}
int Date::operator[] (const char *s)
{
if(s == "year")
return year ;
else if(s == "month")
return month ;
else if(s == "day")
return day ;
else
throw IllegalSubscriptException("Illegal Subscript Exception") ;
}