OOP 日期类外定义(类和对象)

题目描述

定义一个日期类Tdate,其中包括私有属性年月日,并按照输入输出要求完善日期类。(要求成员函数在类外定义,并且不能出现普通函数)

主函数如下:

int main()

{

int a,b,c;

while(cin>>a>>b>>c)

{

Date s;

s.set(a,b,c);

s.nextDay();

s.print();

}

}

不得更改主函数

输入

每一行分别为年月日。

输出

输出当前日期加一天后的结果。

输入样例1 

2019 2 28
2019 3 31
2019 3 30

输出样例1

2019/3/1
2019/4/1
2019/3/31

思路分析

考查类的定义和类的数据成员引用以及类的成员函数使用。

一般把数据成员定义为私有型,把成员函数定义为公有型。

然后我们来看这道题,主要就是实现计算日期的下一天的功能。

我们首先分成两大类,一是闰年,二是不是闰年。

然后大类里面分成五种情况,首先是下一天到了下一个月的情况,二月特殊先判断,然后判断天数为31天的月份,然后是天数为30天的月份,然后是下一天到了下一年的情况,之后是一般情况就直接day加一完事。

AC代码

#include"iostream"
#include"iomanip"
#include"cmath"
using namespace std;
//-----类定义------
class Date
{
	private:
		int year,month,day;
	public:
		void set(int year,int month,int day);
		void nextDay();
		void print();
};
//-----类实现------ 
void Date::set(int year,int month, int day)
{
	this->year=year;
	this->month=month;
	this->day=day; 
}
void Date::nextDay()
{
	if(year%100!=0&&year%4==0||year%400==0)
	{
		if(month==2&&day==28)
		{
			day++;
			return;
		}
		if(month==1||month==3||month==5||month==7||month==8||month==10)
		{
			if(day==31)
			{
				month++;
				day=1;
				return;
			}
		}
		if(month==4||month==6||month==8||month==9||month==11)
		{
			if(day==30)
			{
				month++;
				day=1;
				return;
			}
		}
		if(month==12&&day==31)
		{
			year++;
			month=1;
			day=1;
			return;
		}
		day++;		
	}
	else
	{
		if(month==2&&day==28)
		{
			month++;
			day=1;
			return;
		}
		if(month==1||month==3||month==5||month==7||month==8||month==10)
		{
			if(day==31)
			{
				month++;
				day=1;
				return;
			}
		}
		if(month==4||month==6||month==8||month==9||month==11)
		{
			if(day==30)
			{
				month++;
				day=1;
				return;
			}
		}
		if(month==12&&day==31)
		{
			year++;
			month=1;
			day=1;
			return;
		}
		day++;		
	}
}
void Date::print()
{
	cout<<year<<'/'<<month<<'/'<<day<<endl;
}
//-----主函数------ 
int main()
{
 int a,b,c;
 while(cin>>a>>b>>c)
 {
 Date s;
 s.set(a,b,c);
 s.nextDay();
 s.print();
 }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaolinYe(叶茂林)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值