1449396

练习14.49:

为上一题提到的类定义一个转换目标是bool的类型转换运算符,

先不用在意这么做是否应该。

【出题思路】

本题练习类型转换运算符。

【解答】

class Date{
public:
    explicit operator bool()
    {
        vector<vector<int> > days_per_month = {
            {31, 28, 31, 30, 31,  31, 30, 31, 30, 31},
            {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        };
        return 1 <=month && month <= 12 && 
	       1 <= day && day <= days_per_month[isLeapYear() ? 1 : 0] [month - 1 ];
    }
    
    bool isLeapYear()
    {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
private:
    int year,month,day;
    //其他成员
};