当前位置:首页 C++ > 正文

C++ 编写一个程序,设计一个满足如下要求的CDate类

作者:野牛程序员:2023-06-29 15:52:17 C++阅读 2651

C++ 编写一个程序,设计一个满足如下要求的CDate类:

(1)用/月/年格式输出日期。(2)可运行日期加一天的操作。(3)设置日期。

以下是一个使用C++编写的CDate类,满足您提出的要求:

#include <iostream>
using namespace std;

class CDate {
private:
    int day;
    int month;
    int year;

    bool isLeapYear(int year) {
        return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
    }

    int getDaysInMonth(int month, int year) {
        static const int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        return (month == 2 && isLeapYear(year)) ? 29 : daysInMonth[month - 1];
    }

public:
    CDate(int day, int month, int year) {
        setDate(day, month, year);
    }

    void setDate(int day, int month, int year) {
        this->day = day;
        this->month = month;
        this->year = year;
    }

    void printDate() {
        cout << day << "/" << month << "/" << year << endl;
    }

    void incrementDay() {
        int daysInCurrentMonth = getDaysInMonth(month, year);

        if (day < daysInCurrentMonth) {
            day++;
        } else {
            day = 1;
            if (month < 12) {
                month++;
            } else {
                month = 1;
                year++;
            }
        }
    }
};

int main() {
    CDate date(31, 12, 2022);

    cout << "初始日期:";
    date.printDate();

    cout << "日期加一天:";
    date.incrementDay();
    date.printDate();

    cout << "设置日期为2/7/2023:";
    date.setDate(2, 7, 2023);
    date.printDate();

    return 0;
}

在上述代码中,CDate类具有setDate用于设置日期,printDate用于以"/月/年"的格式输出日期,以及incrementDay用于将日期增加一天的操作。

main函数中,我们创建了一个CDate对象,并演示了使用这些功能的示例。首先,我们输出初始日期,然后进行日期加一天的操作,最后将日期设置为另一个日期并输出。

注意:这个实现假设传入的日期是合法的,并没有做过多的输入验证。在实际应用中,您可能需要添加额外的验证来确保输入的正确性。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击