①定义 date 类对象 d1、d2,分别用于表示 2020 年 5 月 8 日、默
认日期;
②对 d1、d2 进行比较,并输出较小者的日期;
③动态建立 datetime 类对象以表示 2020 年 4 月 14 日 8 时 0 分 0
秒,并定义指针变量 p 使其指向该对象;
④为 p 所指向的对象增加 100 秒,并输出运算后的对象信息;
⑤撤销 p 所指向的对象。
#include<iostream>
using namespace std;
class date
{
protected:
int year,month,day;
public:
date()
{
year=1970;
month=1;
day=1;
}
date(int year,int month,int day)
{
this->year=year;
this->month=month;
this->day=day;
}
void show()
{
cout<<year<<"年-"<<month<<"月-"<<day<<"日";
}
bool operator<(date &d)
{
if(year<d.year) return true;
if(year==d.year&&month<d.month) return true;
if(year==d.year&&month==d.month&&day<d.day) return true;
return false;
}
};
class datetime:public date
{
private:
int hour,min,sec;
public:
datetime()
{
date();
hour=12;
min=0;
sec=0;
}
datetime(int year,int month,int day,int hour,int min,int sec):date(year,month,day)
{
this->hour=hour;
this->min=min;
this->sec=sec;
}
void showT()
{
show();
cout<<" "<<hour<<":"<<min<<":"<<sec<<endl;
}
friend datetime operator+(datetime &t,int k);
};
datetime operator+(datetime &t,int k)
{
datetime tt;
tt.year=t.year;
tt.month=t.month;
tt.day=t.day;
int h=k/3600;
int m=(k%3600)/60;
int s=k%60;
tt.hour=t.hour+h;
tt.min=t.min+m;
tt.sec=t.sec+s;
return tt;
}
int main()
{
//①定义 date 类对象 d1、d2,分别用于表示 2020 年 5 月 8 日、默认日期;
date d1(2020,5,8);
date d2;
//②对 d1、d2 进行比较,并输出较小者的日期;
if(d1<d2)
{
d1.show();
}else{
d2.show();
}
cout<<endl;
//③动态建立 datetime 类对象以表示 2020 年 4 月 14 日 8 时 0 分 0秒,并定义指针变量 p 使其指向该对象;
datetime *p;
p=new datetime(2020,4,14,8,0,0);
//④为 p 所指向的对象增加 100 秒,并输出运算后的对象信息;
(*p)=(*p)+100;
p->showT();
//⑤撤销 p 所指向的对象。
delete p;
return 0;
}