日期类++与>重载

问题描述】

设计符合下述要求的日期类(Date),使得下述代码可以正常运行。

  1. 拥有数据成员year、month和day,分别存储年、月、日;

  2. 构造函数接受年、月、日参数并初始化全部数据成员;

  3. 公有成员函数toText()返回一个string对象,该字符串为该日期对象的文字表达,比如“2022-5-20”;

  4. 重载运算符++,返回一个Date对象,表示该日期的后一天;

  5. 重载运算符>,比较两个Date对象,表示两个日期的先后关系。

【提示】

可以使用to_string()函数将整型变量转成string

string s;

s=to_string(102);

【样例输入】

2023 12 31

2024 1 5


【样例输出】

Date1 is 2023-12-31

Date2 is 2024-1-5

Date1 is not bigger!

Next day of Date1 is 2024-1-1

#include <iostream>  
#include <string>  
using namespace std;  
  
// 用于处理月份天数和闰年的辅助函数  
bool isLeapYear(int year) {  
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);  
}  
  
int daysInMonth(int year, int month) {  
    int daysPerMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  
    if (month == 2 && isLeapYear(year)) {  
        return 29;  
    }  
    return daysPerMonth[month];  
}  
  
class Date {  
private:  
    int year;  
    int month;  
    int day;  
  
public:  
    // 构造函数  
    Date(int y, int m, int d) : year(y), month(m), day(d) {  
        // 这里可以添加对日期的有效性检查  
    }  
  
    // toText 函数  
    string toText() const {  
        return to_string(year) + '-' +  
               (month < 10 ? "0" : "") + to_string(month) + '-' +  
               (day < 10 ? "0" : "") + to_string(day);  
    }  
  
    // 重载++运算符  
    Date& operator++() {  
        day++;  
        if (day > daysInMonth(year, month)) {  
            day = 1;  
            month++;  
            if (month > 12) {  
                month = 1;  
                year++;  
            }  
        }  
        return *this;  
    }  
  
    // 重载>运算符  
    bool operator>(const Date& other) const {  
        if (year > other.year) return true;  
        if (year < other.year) return false;  
        if (month > other.month) return true;  
        if (month < other.month) return false;  
        return day > other.day;  
    }  
};  
  
int main() {  
    int year1, month1, day1;  
    cin >> year1 >> month1 >> day1;  
    Date d1(year1, month1, day1);  
  
    int year2, month2, day2;  
    cin >> year2 >> month2 >> day2;  
    Date d2(year2, month2, day2);  
  
    cout << "Date1 is " << d1.toText() << endl;  
    cout << "Date2 is " << d2.toText() << endl;  
  
    if (d1 > d2)  
        cout << "Date1 is bigger!" << endl;  
    else  
        cout << "Date1 is not bigger!" << endl;  
  
    cout << "Next day of Date1 is " << (++d1).toText() << endl;  
  
    return 0;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值