資源簡介
用c++設計一個日期類Date,包括年、月、日等私有數據成員。要求實現日期的基本運算,如一日期加上天數、一日期減去天數、兩日期相差的天數等。
代碼片段和文件信息
#include
#include
class?Date
{
public:
friend?Date?operator?+?(Date?Day??int?Days);//返回一日期加一天數得到的日期
friend?Date?operator?-?(Date?Day??int?Days);//返回一日期減去天數得到的日期?
friend?int?operator?-?(Date?&aDate?&b);//返回兩日期相差的天數
Date();//構造函數,初始化各變量
void?input();
void?output();
private:
bool?leap(int?years);//?判斷指定的年份是否為閏年
int?dton(Date&?a);//將指定日期轉換為從1年1月1日起的天數
Date?ntod(int?days);//將指定的1年1月1日起的天數轉換為對應的日期
int?year;
int?month;
int?day;
};
int?main()
{
????Date?datedate1date2;
int?daysdays1days2;
date.input();
cout?<“The?date?you?entered?in?is:\n“?<“date:“;
date.output();
cout?<“******************************************************************************\n“;
cout?<“Please?enter?the?days?you?want?to?add:\n“;
cin?>>?days1;
cout?<“******************************************************************************\n“;
date1=date+days1;
cout?<“the?date?after?add?the?days?is:\n“?<“date1:“;
date1.output();
cout?<“******************************************************************************\n“;
cout?<“Please?enter?the?days?you?want?to?minus:\n“;
cin?>>?days2;
cout?<“******************************************************************************\n“;
date2=date1-days2;
cout?<“the?date?after?minus?the?days?is:\n“?<“date2:“;
date2.output();
cout?<“******************************************************************************\n“;
????cout?<“The?days?added?and?the?days?minused?discrepancy?is:\n“?<“date1-date2=?“;
days=date1-date2;
cout?< cout?<“******************************************************************************\n“;
return?0;
}
void?Date::input()
{
cout?<“******************************************************************************\n“;
cout?<“Please?input?a??yearmonth?and?day!(like:1?1?1):\n“;
cin?>>?year?>>?month?>>?day;
if(year<0||month>12||month<1||day>31||day<1||(leap(year)&&month==2&&day>29)||(!leap(year)&&month==2&&day>28))
{//判斷輸入的日期是否合法
cout<<“Please?input?again!\nthe?date?you?have?entered?is?wrong!\n“;
}
cout?<“******************************************************************************\n“;
}
void?Date::output()
{
cout?<}
bool?Date::leap(int?years)
{
if((years%4==0
- 上一篇:計算機圖形學OpenGL畫機器人
- 下一篇:C語言電子表格
評論
共有 條評論