c++---运算符重载

  • 设计一个日期类Date,包括年、月、日等私有数据成员。

要求:

  • 实现日期的基本运算,如一日期加上天数、一日期减去天数、两日期相差的天数等。
  • 要求:使用运算符重载。(为便于计算,我们假设每月的天数都是30天) 
#include <iostream>
#include<algorithm>
using namespace std;
class Date
{
public:
    Date()
    {
        d=0;
        r=0;
        y=0;
        date=0;
    }
    Date(int d,int r,int y)
    {
        this->d=d;
        this->r=r;
        this->y=y;
    }
    Date(int da)
    {
        d=da;
        y=0;
        r=0;
    }

    friend Date operator+(Date c1,Date c2);
    friend Date operator-(Date c1,Date c2);
    friend Date operator-=(Date &c1,Date &c2);
    void display()
    {
        cout<<y<<"年 "<<r<<"月 "<<d<<"日"<<endl;
    }

    void print()
    {
        cout<<date;
    }
private:
    int d;
    int r;
    int y;
    int date;
};

Date operator+(Date c1,Date c2)
{
    c1.d=c1.d+c2.d;
    int x=c1.d/30;
    c1.d=c1.d%30;
    c1.r=c1.r+x;
    int y=c1.r/12;
    c1.r=c1.r%12;
    c1.y=c1.y+y;
    return c1;
}

Date operator-(Date c1,Date c2)
{
    c1.d-=c2.d;
    while(c1.d<0)
    {
        c1.r--;
        c1.d=c1.d+30;
    }
    while(c1.r<0)
    {
        c1.y--;
        c1.r=c1.r+12;
    }

    return c1;
}

Date operator-=(Date &c1,Date &c2)
{
    int x1,x2;
    x1=c1.r*30;
    x2=c2.r*30;

    int y1,y2;
    y1=c1.y*360;
    y2=c2.y*360;

    int sum1,sum2;
    sum1=c1.d+x1+y1;
    sum2=c2.d+x2+y2;

    c1.date=abs(sum1-sum2);
    return c1;
}
int main()
{
    Date c1(24,12,2019),c2(21,12,2019),c3,c4,c5;

    cout<<"c1 = ";
    c1.display();

    cout<<"c2 = ";
    c2.display();

    cout<<"日期加上天数 : ";
    c3=c1+11;
    c3.display();

    cout<<"日期减去天数 : ";
    c4=c2-22;
    c4.display();

    cout<<"两日期相差的天数 : ";
    c1-=c2;
    c1.print();

    return 0;
}

结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值