用Qt creator编写一个表示具体日期的日期类。类中年、月、日属性作为私有数据成员;定义必要的无参构造函数、带参构造函数等;分别定义不同的成员函数实现对私有数据成员的设置和访问(如getYear()函数返回年份);定义用于显示日期信息的成员函数;编写主函数测试类及各成员函数的使用。的代码及运行结果图片
4条回答 默认 最新
阿里嘎多学长 2025-12-05 19:19关注阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程
日期类实现
以下是用Qt Creator编写一个表示具体日期的日期类的实现:
#ifndef DATE_H #define DATE_H #include <QDate> class Date { private: int year; int month; int day; public: // 无参构造函数 Date(); // 带参构造函数 Date(int year, int month, int day); // 设置年 void setYear(int year); // 设置月 void setMonth(int month); // 设置日 void setDay(int day); // 获取年 int getYear(); // 获取月 int getMonth(); // 获取日 int getDay(); // 重载<<运算符 friend QDebug operator<<(QDebug dbg, const Date &date); }; #endif // DATE_H#include "date.h" #include <QDebug> Date::Date() : year(0), month(0), day(0) {} Date::Date(int year, int month, int day) : year(year), month(month), day(day) {} void Date::setYear(int year) { this->year = year; } void Date::setMonth(int month) { this->month = month; } void Date::setDay(int day) { this->day = day; } int Date::getYear() { return year; } int Date::getMonth() { return month; } int Date::getDay() { return day; } QDebug operator<<(QDebug dbg, const Date &date) { dbg << "Date(" << date.year << ", " << date.month << ", " << date.day << ")"; return dbg; }使用示例
int main() { Date date(2022, 12, 25); qDebug() << date; date.setYear(2023); date.setMonth(1); date.setDay(1); qDebug() << date; return 0; }在上面的代码中,我们定义了一个名为
Date的类,包含了年、月、日的私有数据成员,以及对应的成员函数。我们还重载了QDebug的<<运算符,以便可以方便地输出Date对象的信息。解决 无用评论 打赏 举报