设计一个日期类Date要求:使用运算符重载。

3.  设计一个日期类Date,包括年、月、日等私有数据成员。要求实现日期的基本运算,如一日期加上天数、一日期减去天数、两日期相差的天数等。要求:使用运算符重载。

 


#include<iostream>
using namespace std;

class Date
{
public:
    Date(int y, int m, int d)
    {
        year = y;
        mouth = m;
        day = d;
    }
    void InputDate()
    {
        cin >> year >> mouth >> day;
    }
    Date operator+(Date &c);
    Date operator-(Date &c);
    int operator&(Date &c2);
    void display();
    ~Date(){}


private:
    int year;
    int mouth;
    int day;
};

Date Date::operator+(Date &c)
{
    Date d(0, 0, 0);
    d.day = day + c.day;
    d.year = year;
    d.mouth = mouth;
    if(d.day > 30)
    {
        d.mouth = mouth + 1;
        d.day = 1;
    }
    if(d.mouth > 12)
    {
        d.year = year + 1;
        d.mouth = 1;
    }
    return d;
}

Date Date::operator-(Date &c)
{
    Date d(0, 0, 0);
    d.day = day - c.day;
    d.year = year;
    d.mouth = mouth;
    if(d.day < 0)
    {
        d.day = 30;
        d.mouth = mouth - 1;
    }
    if(d.mouth < 0)
    {
        d.mouth = 1;
        d.year = year - 1;
    }
    return d;
}

int Date::operator&(Date &c2)
{
    Date c(0, 0, 0);
    int x = 0;
    if(day > c2.day)
    {
        c.day = day - c2.day;
    }
    if(day < c2.day)
    {
        c.day = c2.day - day;
    }
    if(mouth > c2.mouth)
    {
        c.mouth = mouth - c2.mouth;
    }
    if(mouth < c2.mouth)
    {
        c.mouth = c2.mouth - mouth;
    }
    if(year > c2.year)
    {
        c.year = year - c2.year;
    }
    if(year < c2.year)
    {
        c.year = c2.year - year;
    }
    x = c.day + c.mouth * 30 + c.year * 365;
    return x;
}

void Date::display()
{
    if(year != 0 && mouth != 0)
    {
         cout << year << "年" << mouth << "月" << day << "日" << endl;
    }

    else
    {
        cout << day << "天" << endl;
    }
}
int main(void)
{
    Date c1(0, 0, 0), c2(0, 0, 0), c3(0,0,4), c4(0,0,1);

    cout << "输入日期的格式年 月 日" << endl;
    cout << "Please input the first Date:";
    c1.InputDate();
    cout << "Please input the second Date:";
    c2.InputDate();

    cout << "输入加减天数的格式0 0 天数" << endl;
    cout << "Please input the add num:";
    c3.InputDate();
    Date c(0, 0, 0);

    c = c1 + c3;
    cout << "c1 + day =" << endl;
    c.display();
    cout << "Please input the sub num:";
    c4.InputDate();
    c = c1 - c4;
    cout << "c1 - day = " << endl;
    c.display();
    int m = 0;
    m = c1 & c2;
    cout << endl << endl <<"第一个日期为:" << endl;
    c1.display();

    cout << "第二个日期为:" << endl;
    c2.display();
    cout << endl << "c1 - c2的天数为:" << m << endl;

    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值