06-B. Date(类与构造)

本文详细介绍了如何在日期类中实现构造函数、setDate方法,以及根据闰年规则计算明天日期的功能,包括对2月特殊情况的处理。通过实例展示了如何使用这些方法进行日期操作和测试。

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

06-构造和析构-

题目描述
下面是一个日期类的定义,请在类外实现其所有的方法,并在主函数中生成对象测试之。
在这里插入图片描述
注意,在判断明天日期时,要加入跨月、跨年、闰年的判断

例如9.月30日的明天是10月1日,12月31日的明天是第二年的1月1日

2月28日的明天要区分是否闰年,闰年则是2月29日,非闰年则是3月1日

输入
测试数据的组数t

第一组测试数据的年 月 日



要求第一个日期的年月日初始化采用构造函数,第二个日期的年月日初始化采用setDate方法,第三个日期又采用构造函数,第四个日期又采用setDate方法,以此类推。

输出
输出今天的日期

输出明天的日期

#include <iostream>
#include <iomanip>
using namespace std;

class date
{
    int year,month,day;
public:
    date()
    {year=0;month=0;day=0;}
    date(int y,int m,int d)
    {year=y;month=m;day=d;}
    int gety()
    {return year;}
    int getm()
    {return month;}
    int getd()
    {return day;}
    void setdate(int y,int m,int d)
    {year=y;month=m;day=d;}
    void print()
    {
        cout<<year<<"/";
        if(month<10)
            cout<<"0"<<month<<"/";
        else
            cout<<month<<"/";
        
        if(day<10)
            cout<<"0"<<day<<endl;
        else
            cout<<day<<endl;
    }
    void addoneday()
    {
        if(month==1||month==3||month==5||month==7||month==8||month==10)
        {
            if(day==31)
            {
                day=1;month++;
            }
            else
                day++;
        }
        else if(month==12)
        {
            if(day==31)
            {
                day=1;month=1;year++;
            }
            else
                day++;
        }
        else if(month==4||month==6||month==9||month==11)
        {
            if(day==30)
            {
                month++;day=1;
            }
            else
                day++;
        }
        else if(month==2)
        {
            if(year%4==0)
            {
                if(day==29)
                {
                    day=1;month++;
                }
                else
                    day++;
            }
            else
            {
                if(day==28)
                {
                    month++;day=1;
                }
                else
                    day++;
            }
        }
    }
};

int main()
{
    int t,i;
    cin>>t;
    for(i=1;i<=t;i++)
    {
        int y,m,d;
        cin>>y>>m>>d;
        if(i%2!=0)
        {
            date d1(y,m,d);
            cout<<"Today is ";
            d1.print();
            cout<<"Tomorrow is ";
            d1.addoneday();
            d1.print();
        }
        else
        {
            date d1;
            d1.setdate(y,m,d);
            cout<<"Today is ";
            d1.print();
            cout<<"Tomorrow is ";
            d1.addoneday();
            d1.print();
        }
    }
    return  0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值