实验一 类和对象(一)

实验一 类和对象(一)

定义一个满足如下要求的Date类和对象。
(1)其数据成员包括day、month、year;
(2)可设置日期;
(3)用下面的格式输出日期:日/月/年;
(4)可运行在日期上加一天操作(如果是闰年的2月);
(5)可判断是否是闰年;
(6)定义Date对象,设置时间,输出该对象提供的时间。

实验步骤
(1)将年、月、日作为私有成员予以保护。
(2)setDate()用来设置具体日期,缺省值为1970年1月1日。
(3)plusOneDay()用来将日期加一,但是特别考虑了需要对月份、年份进位加一的情形。
(4)isLeap()则用来判断现在的年份是不是闰年。

完整代码

#include <iostream>
using namespace std;

class Date
{
	public:
	Date()
	{
		year=1970;
	    month=1;
    	day=1;
	}
	void setDate();
	void plusOneDay();
	void isLeap();
	private:
	int day;
	int month;
	int year;
};

void Date::setDate()
{
	cout<<"当前日期为:"<<day<<"/"<<month<<"/"<<year<<endl;
	cout<<"年:";
	cin>>year;
    cout<<"月:";
	cin>>month;
	cout<<"日:";
	cin>>day;
	cout<<"当前日期为:"<<day<<"/"<<month<<"/"<<year<<endl;
}
void Date::plusOneDay()
{
	if(day==31&&(month==1||month==3||month==5||month==7||month==8||month==10))
	{
		day=1;
		month++;
	}
	else if(day==31&&month==12)
	{
		day=1;
		month=1;
		year++;
	}
	else if(day==30&&(month==4||month==6||month==9||month==11))
	{
		day=1;
		month++;
	}
	else if(day==28&&month==2&&(year%4!=0||(year%100==0&&year%400!=0)))
	{
		day=1;
		month++;
	}
	else if(day==29&&month==2&&((year%4==0&&year%100!=0)||year%400==0))
	{
		day=1;
		month++;
	}
	else
	{
		day++;
	}
	cout<<"当前日期为:"<<day<<"/"<<month<<"/"<<year<<endl;
}
void Date::isLeap()
{
	if((year%4==0&&year%100!=0)||year%400==0)
	{
		cout<<"该年份是闰年。"<<endl<<endl; 
	}
	else
	{
		cout<<"该年份不是闰年。"<<endl<<endl; 
	}
}

int main()
{
	int putin;
	Date date;
	while(1)
	{
		
	    cout<<"输入1:设置日期"<<endl<<"输入2:加一天"<<endl<<"输入3:判断是否为闰年"<<endl;
    	cin>>putin;
    	if(putin==1)
    	{
    		date.setDate();
    	}
    	else if(putin==2)
    	{
    		date.plusOneDay();
    	}
    	else if(putin==3)
    	{
    		date.isLeap();
    	}
    	else
    	{
    		cout<<"输入错误,请重新输入!"<<endl; 
    	}
	}
}

仅作留档。

发布了30 篇原创文章 · 获赞 12 · 访问量 891

猜你喜欢

转载自blog.csdn.net/weixin_43893854/article/details/104321712
今日推荐