面向对象:实验一:the next day

定义一个满足下列要求的类CDate:
1)有三个私有成员数据:年、月、日;
2)有设置日期的公有成员函数。(最好在设置日期的成员函数里加入数据合法检查。)
3)有用格式“年/月/日”输出日期的公有成员函数
4)有对当前日期加一天的公有成员函数。
5)有判断是否为闰年的私有成员函数。
设计主函数,在主函数中创建对象;调用设置日期的成员函数,设置当天的日期;调用输出日期的成员函数输出当天的日期;调用对当前日期加一天的成员函数,然后再调用输出日期的成员函数,输出第二天的日期。
注意:闰年的2月的天数为29天,其它年份2月28天,闰年是指:年份能被4且不能被100整除,或者年份能被400整除。


#pragma once
#include <iostream>
using namespace std;
class CDate
{
private:
	int year;
	int month;
	int day;
	bool Ryear()
	{
		if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
			return true;
		else
			return false;
	}
public:
	void setdate();
	void getdate();
	void newdate();
};
#include <iostream>
#include "CDate.h"
using namespace std;
int main()
{
	CDate d1;  //定义 d1 为 类CDate 的对象
	d1.setdate();  //调用对象 d1 的成员函数setdate
	d1.newdate();  //调用对象 d1 的成员函数newdate
	d1.getdate();  //调用对象 d1 的成员函数getdate
}
void CDate::setdate()  //在类外定义函数setdate() 
{
	cout << "please enter year,month,day:" << endl; //输入当前日期
	cin >> year >> month ;
	while (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
	{             //应用while语句进行循环判断,输入的日期是否符合逻辑,否则重新输入(大月最多有31天)
		cin >> day;
		if (day >= 1 && day <= 31)
			break;
		cout << "please enter again(1-31):";
	}
	while (month == 4 || month == 6 || month == 9 || month == 11)   //(小月最多有30天)
	{
		cin >> day;
		if (day >= 1 && day <= 30)
			break;
		cout << "please enter again(1-30):";
	}
	while (month == 2)   //2月时,闰年有29天,平年有28天
	{
		cin >> day;
		if (Ryear())   //调用函数,判断是否为闰年
		{
            if (day >= 1 && day <= 29)
			    break;
				cout << "please enter day again(1-29):";
        }
		else
		{
			if (day >= 1 && day <= 28)
				break;
			cout << "please enter day again(1-28):";
		}		
	}
}
void CDate::newdate()
{
	switch (month)  //运用switch语句进行运算
	{
	case 1:       //大月(除了12月)的情况下,小于31天时第二天day+1,等于31天时,第二天变成了下一个月1号
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	{
		if (day < 31)
			day++;
		else
		{
			day = 1;
			month++;
		}
	}
	case 4:       //小月的情况下,小于30天时第二天day+1,等于30天时,第二天变成了下一个月1号
	case 6:
	case 9:
	{
		if (day < 30)
			day++;
		else
		{
			day = 1;
			month++;
		}
	}break;
	case 12:     //12月的情况下,小于31天时第二天day+1,等于31天时,第二天变成了下一年的1月1号
	{
		if (day < 31)
			day++;
		else
		{
			day = 1;
			month = 1;
			year++;
		}
	}break;
	case 2:    //2月时,需先判断是否为闰年,在判断小于28(29)天时第二天day+1,等于28(29)天时,第二天变成了下一个月1号
	{
		if (Ryear())
		{
			if (day < 29)
				day++;
			else
			{
				day = 1;
				month++;
			}break;
		}
		if (day < 28)
			day++;
		else
		{
			day = 1;
			month++;
		}break;
	}
	}
}
void CDate::getdate()
{
	cout << "the next day is :" << year << "/" << month << "/" << day << endl;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值