定义日期类Date,并重载运算符实现几种操作

本文介绍了一个日期类的设计与实现,包括日期加减操作、日期间隔计算及星期查询功能。通过C++代码示例展示了如何重载运算符来实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要求这样:定义一日期Date类,重载++,--,-和^ 运算,分别完成求日期+1,-1, 两个日期相减之间天数,以及取对应日期的星期几的操作,并编写主函数进行测试。

代码:

Date类

</pre><pre name="code" class="cpp">//
//  Date.h
//  Date
//
//  Created by KevinLee on 15/10/13.
//  Copyright © 2015年 KevinLee. All rights reserved.
//

#include <iostream>
#include <math.h>
using namespace std;
static int dom1[12]={31,28,31,30,31,30,31,31,30,31,30,31};//Day of Month 平年
static int dom2[12]={31,29,31,30,31,30,31,31,30,31,30,31};//Day of Month 闰年
bool isLeap(int year){//判断是否是闰年
    return (year%4==0&&year%100!=0)||year%400==0?true:false;
}
class Date{
private:
    int year,month,day;
public:
    Date(int y,int m,int d){
        year=y;month=m;day=d;
        cout<<"New Date:["<<y<<"-"<<m<<"-"<<d<<"]"<<endl;
        if(year<1900){
            cout<<"The year cannot be smaller than 1900!"<<endl;//年份不能小于1900
            year=1900;
        }
        if(month<0||month>12) {
            cout<<"Wrong month!"<<endl;//月份输入不正确
            month=1;
        }
        if((isLeap(year)&&day>dom2[month-1])||day<1||(isLeap(year)==false&&day>dom1[month-1])){
            cout<<"Wrong day!"<<endl;//天数输入不正确
                day=1;
            }
    }
    Date(string){
        year=1900;month=1;day=1;
    }
    Date(){};
    Date operator++(int);//日期加1
    Date operator--(int);//日期减1
    int operator-(Date);//求两个日期之间的间隔天数
    string operator^(int);//求日期之后多少天是星期几,0代表当天
    int countDays();//计算一天在一年中的第几天
    void show(){
        cout<<year<<"-"<<month<<"-"<<day<<endl;
    }
};

int Date::countDays(){
    int days=0;
    if (isLeap(year)) {
        for (int i=0; i<month-1; i++) {
            days+=dom2[i];
        }
        days+=day;
    }
    else{
        for (int i=0; i<month-1; i++) {
            days+=dom1[i];
        }
        days+=day;
    }
    return days;
}

Date Date::operator++(int i){
    if (isLeap(year)) {
        if (day==dom2[month-1]) {
            day=1;
            month++;
            if (month>12) {
                year++;
                month=1;
            }
        }
        else{
            day++;
        }
    }
    else{
        if (day==dom1[month-1]) {
            day=1;
            month++;
            if (month>12) {
                year++;
                month=1;
            }
        }
        else{
            day++;
        }
    }
    return *this;
}
Date Date::operator--(int i){
    if (isLeap(year)) {
        if (day==1) {
            month--;
            if (month<1) {
                year--;
                month=12;
            }
            day=dom2[month-1];
        }
        else{
            day--;
        }
    }
    else{
        if (day==1) {
            month--;
            if (month<1) {
                year--;
                month=12;
            }
            day=dom1[month-1];
        }
        else{
            day--;
        }
    }
    return *this;
}

int Date::operator-(Date other){//利用成员函数重载
    int subDay=0;
    if(this->year==other.year){
        subDay+=abs(this->countDays()-other.countDays());
    }
    else{
        if(this->year<other.year){//交换两个相减的日期,保证前者在后者之后
            Date temp;
            temp=*this;
            *this=other;
            other=temp;
        }
        if(this->year-other.year>2){
            for(int i=1;i<this->year-other.year;i++){
                subDay+=365;
                if(isLeap(other.year+i)){
                    subDay+=1;
                }
            }
        }
        subDay+=365-other.countDays()+this->countDays();
        if(isLeap(other.year)) subDay++;
    }
    return subDay;
}
string Date::operator^(int i){
    string str[7]={"Mon","Tue","Wed","Thur","Fri","Sat","Sun"};
    Date date("19000101");//已知1900年1月1日为星期一
    int flag;
    int day=*this-date+i;
    flag=day%7;
    return str[flag];
}

测试主函数:

//
//  main.cpp
//  Date
//
//  Created by KevinLee on 15/10/13.
//  Copyright © 2015年 KevinLee. All rights reserved.
//

#include <iostream>
#include "Date.h"
using namespace std;
int main(int argc, const char * argv[]) {
    Date date(2012,2,29),date2(2013,3,1),date3(2015,10,14);
    (date++).show();
    (date--).show();
    date.show();
    date2.show();
    date3.show();
    cout<<date-date2<<endl;//求两个日期间隔天数
    string str=date3^0;//^符号接天数
    cout<<str<<endl;
    return 0;
}




### C++ 中 `Date` 运算符重载实现 #### 赋值运算符 (`=`) 的重载 为了防止浅拷贝带来的问题,在自定义中通常需要显式地重载赋值运算符。对于 `Date` 而言,其赋值运算符重载如下所示: ```cpp class Date { public: // 构造函数其他成员函数... // 赋值运算符重载 Date& operator=(const Date& d) { if (this != &d) { // 防止自我赋值 _year = d._year; _month = d._month; _day = d._day; } return *this; // 返回当前对象的引用以便链式赋值 } private: int _year; int _month; int _day; }; ``` 此段代码展示了如何通过复制另一个实例的数据来更新现有实例的内容[^1]。 #### 加法运算符 (`+`) 的重载 当涉及到两个日期相加或将整数值作为天数加到某个特定日期上时,可以这样设计加法运算符: ```cpp // 成员函数形式 Date operator+(int daysToAdd) const { Date result(*this); result.addDays(daysToAdd); // 假设有一个addDays方法用于处理具体逻辑 return result; } // 友元函数形式(允许不同型的右操作数) friend Date operator+(const Date& lhs, const Date& rhs); // 或者支持不同型混合计算 friend Date operator+(const Date& date, double dayOffset); ``` 这里提供了两种方式:一种是在内部定义为成员函数;另一种则是声明成友元函数以接受不同的参数组合[^2]。 #### 关系运算符 (`<`, `<=`, `>`, `>=`) 的重载 关系运算符可以通过复用来简化编码工作量并提高一致性。一旦实现了基本的关系判断如 `<` `==` ,其他几个就可以基于这两个构建起来: ```cpp bool operator<(const Date& other) const { // 实际比较的具体实现... } bool operator==(const Date& other) const { // 判断两日期是否完全相同... } // 使用已有的 < == 来推导其余的关系运算符 bool operator<=(const Date& other) const { return !(*this > other); } bool operator>(const Date& other) const { return !(*this <= other); } bool operator>=(const Date& other) const { return !(*this < other); } ``` 这种方法不仅减少了重复劳动还强了程序的一致性可维护性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值