天天看點

Timedate

構造一個日期時間類(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)