|
|
发表于 2012-9-19 23:38:27
|
显示全部楼层
- /*
- 2。定义一个日期类date,数据成员有year,month,day。成员函数有:私有成员函数int isleap()判断year是否是闰年,
- 若是返回1,否则返回0。
- (2)私有成员函数int check()判断日期是否合法,若合法返回1,若不合法返回0。
- (3)设置年,月,日,并检测是否为合法日期。
- (4)按yyyy/mm/dd格式输出日期,若是闰年,还要输出是否是闰年的信息。
- 在主函数中定义一个日期类对象,任意输入年、月、日值,然后对若有成员函数进行测试。
- */
- #include <iostream>
- using namespace std;
- class BadDate{};
- class Date {
- public:
- Date();
- void setDate( int y, int m, int d )throw (BadDate);
- void output()const;
- private:
- int isleap()const;
- int check()const;
- int m_year;
- int m_month;
- int m_day;
- };
- Date::Date():m_year(2012), m_month(9), m_day(19) {
- }
- void Date::setDate( int y, int m, int d ) throw (BadDate){
- m_year = y;
- m_month = m;
- m_day = d;
- if (!check()) throw BadDate();
- }
- void Date::output()const {
- cout<<m_year<<"/"<<m_month<<"/"<<m_day<<endl;
- cout<<(isleap()?"is Leap year\n":"");
- }
- int Date::isleap()const {
- return (m_year%400==0)||((m_year%4==0)&&(m_year%100!=0));
- }
- int Date::check()const {
- int check_year = ( m_year > 0 );
- int check_month = ( 1 <= m_month && m_month <= 12 );
- static int days[]={0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- int check_day = (
- (1 <= m_day && m_day <= days[m_month])&&
- ( ( m_month==2 && !isleap() )?(m_day<=28):1 )
- );
- return check_year && check_month && check_day;
- }
- int main() {
- try{
- Date d1;
- d1.output();
- d1.setDate(2011,7,30);
- d1.output();
- d1.setDate(2012,2,30);
- d1.output();
- }catch( BadDate& b ) {
- cout<<"bad date value "<<endl;
- }
- }
复制代码 |
|