构造一个日期时间类(Timedate),数据成员包括年、月、日和时、分、秒,函数成员 包括设置日期时间和输出时间,其中年、月请用枚举类型,并完成测试。(包括用成员 函数和用普通函数)
解:本题要求仅是定义类的练习,并非实用的提供日期时间的程序。实用的日期时间程序 见附录二的日期时间函数。
#include <iostream>
#include <iomanip>
using namespace std;
enum YR{Y2000,Y2001,Y2002,Y2003,Y2004,Y2005};
enum MT{Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
class Timedate{
private:
YR year;
MT month;
int date;
int hh;
int mm;
int ss;
public:
Timedate()
{
year=Y2000;
month=Jan;
date=1;
hh=0;
mm=0;
ss=0;
}
Timedate(YR a,MT b,int c)
{
year=a;
month=b;
date=c;
hh=12;
mm=30;
ss=0;
}
void getdate(YR &,MT &,int &);//使用引用一次取得3个数值
void gettime(int &,int &,int &);
void putdate(YR ,MT ,int );
void puttime(int ,int ,int );
void list();
};
void Timedate::getdate(YR &y,MT &m,int &d)
{
y=year; m=month; d=date;
}
void Timedate::gettime(int &a,int &b,int &c)
{
a=hh; b=mm; c=ss;
}
void Timedate::putdate(YR a,MT b,int c)
{
year=a; month=b; date=c;
}
void Timedate::puttime(int a,int b,int c)
{
hh=a; mm=b; ss=c;
}
void Timedate::list()
{//成员函数,直接访问私有的数据成员
cout<<"year/month/date :";
switch(year)
{
case Y2000:cout<<"2000";break; case Y2001:cout<<"2001";break;
case Y2002:cout<<"2002";break; case Y2003:cout<<"2003";break;
case Y2004:cout<<"2004";break; case Y2005:cout<<"2005";break;
}
switch(month)
{
case Jan:cout<<'/'<<"Jan";break;
case Feb:cout<<'/'<<"Feb";break;
case Mar:cout<<'/'<<"Mar";break;
case Apr:cout<<'/'<<"Apr";break;
case May:cout<<'/'<<"May";break;
case Jun:cout<<'/'<<"Jun";break;
case Jul:cout<<'/'<<"Jul";break;
case Aug:cout<<'/'<<"Aug";break;
case Sep:cout<<'/'<<"Sep";break;
case Oct:cout<<'/'<<"Oct";break;
case Nov:cout<<'/'<<"Nov";break;
case Dec:cout<<'/'<<"Dec";break;
}
cout<<'/'<<date<<endl; cout<<"hour:minite:second :";
cout<<hh<<':'<<mm<<':'<<ss<<endl;
}
int main(int argc, char* argv[])
{
Timedate A(Y2004,Mar,3),B;
A.list();
B.list();
B.putdate(Y2005,Oct,18);
B.puttime(17,30,00);
B.list();
return 0;
}
![运行结果!!!](https://img-blog.csdnimg.cn/20181218220721566.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNTczOTkz,size_16,color_FFFFFF,t_70)