定义日期类Date。要求:
(1)可以设置日期;
(2)日期加一天操作;
(3)输出函数,输出格式为“XXXX-XX-XX”;
(4)编写主函数,定义对象,完成相应功能。
程序的参考的输入(“Input Date:”为提示文字):
Input Date:2016 2 28
程序的输出:
2016-2-28
2016-2-2
本程序是由 QTCreator在linux操作系统下完成的,仅供参考
Date类的头文件
#ifndef CDATE_H
#define CDATE_H
class CDate
{
private:
int year;
int month;
int day;
int YearNL[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
int YearL[12]={31,29,31,30,31,30,31,31,30,31,30,31};
char WhileFlag = 'n'; //set a WhileFlag to deal error input
char flagleap='n';
public:
//void SetDate(int year, int month, int day);
void SetDate();
void AddDate();
void GetDate();
char LeapYear();
};
#endif // CDATE_H
Date类的实现
#include "cdate.h"
#include <iostream>
using namespace std;
char CDate::LeapYear()
{
if(( 0 == year%400 ) || ( 0 == year %4&& 0!= year%100 ))
{
cout<<year<<" is a leap year "<<endl<<endl;
//if the year is a leap year then check it with YearL[]
if(day > YearL[month-1])
{
cout <<"invalid value ! input again "<<endl<<endl;
return WhileFlag = 'n';
}
//return the WhileFlag
else
{
return WhileFlag ='y',flagleap='y';
}
}
//if the year is not a leap year then check it with YearNL[]
else
{
if(day > YearNL[month-1])
{
cout <<"invalid value ! input again "<<endl<<endl;
return WhileFlag = 'n';
}
//return the WhileFlag
else
{
return WhileFlag ='y';
}
}
}
void CDate::SetDate()
{
while(WhileFlag == 'n')
{
cout <<"Please input [ year month day ]:";
cin >>year>>month>>day;
this->year = year;
this->month = month;
this->day = day;
cout<<endl<<"Yourinput:"<<year<<"-"<<month<<"-"<<day<<endl<<endl;
LeapYear();
}
}
//add one day
void CDate ::AddDate()
{
//if user input a leap year and the day is 29 ,the tomorrow day will be change
if(( 'y' == flagleap ) && ( day == YearL[month-1] ))
{
day = 1;
cout << "Tomorrow is:"<<year<<"-"<<month+1<<"-"<<day<<endl;
}
//else output directly
else if(day == YearNL[month-1]) //if the day is the end of month,then set the day=1
{
day = 1;
cout << "Tomorrow is:"<<year<<"-"<<month+1<<"-"<<day<<endl<<endl;
}
else //else it can add directly
{
cout << "Tomorrow is:"<<year<<"-"<<month<<"-"<<day+1<<endl<<endl;
}
}
//get the date
void CDate::GetDate()
{
SetDate(); //call the Set() to set date
cout<<"The date is:"<<year<<"-"<<month<<"-"<<day<<endl;
AddDate();
}
Main函数
#include <iostream>
#include "cdate.h"
using namespace std;
int main()
{
CDate Date1; //creat a object Date1
Date1.GetDate(); //call the Get method to obtain date
return 0;
}
运行结果:
为了区别瑞年和平年,我输入了1880 的2月 29日;如图显示
输入的2018年的10月16日: