定义一个日期类Date,数据成员包括年、月、日,SetDate(int y,int m,int d)和PrintDate()函数分别用于设置日期和显示日期;再定义一个时间类Time,数据成员包括时、分、秒,SetTime(int h,int m,int s)和PrintTime()函数分别用于设置时间和显示时间,在此基础上再定义一个日期时间类TimeDate,充分利用已有的两个类中提供的方法,实现日期和时间的设置和显示。请实现类TimeDate,下面是用于测试的主函数及参考运行结果。
int main()
{
TimeDate dt_a,dt_b(2010,4,16,9,30,0);
cout<<"dt_a: ";
dt_a.PrintDate_Time();
cout<<endl;
cout<<"dt_b: ";
dt_b.PrintDate_Time();
dt_a.SetTime(20,00,00);
dt_a.SetDate(2008,8,7);
cout<<endl;
cout<<"dt_after uptate: ";
dt_a.PrintDate_Time();
return 0;
}
代码如下:
#include <iostream>
using namespace std;
class Date
{
protected:
int year,month,day;
public:
Date()
{
year=0;
month=0;
day=0;
}
Date(int y,int m,int d):year(y),month(m),day(d){}
void SetDate(int y,int m,int d);
void PrintDate();
};
void Date::SetDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Date::PrintDate()
{
cout<<year<<"/"<<month<<"/"<<day;
}
class Time
{
protected:
int hour,minute,second;
public:
Time():hour(0),minute(0),second(0){}
Time(int h,int m,int s):hour(h),minute(m),second(s){}
void SetTime(int h,int m,int s);
void PrintTime();
};
void Time::SetTime(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
void Time::PrintTime()
{
cout<<hour<<":"<<minute<<":"<<second;
}
class TimeDate:public Date,public Time
{
public:
TimeDate():Date(),Time(){}
TimeDate(int y,int mo,int d,int h,int mi,int s):Date(y,mo,d),Time(h,mi,s){}
void PrintDate_Time();
};
void TimeDate::PrintDate_Time()
{
PrintDate();
cout<<"\t";
PrintTime();
}
int main()
{
TimeDate dt_a,dt_b(2010,4,16,9,30,0);
cout<<"dt_a: ";
dt_a.PrintDate_Time();
cout<<endl;
cout<<"dt_b: ";
dt_b.PrintDate_Time();
dt_a.SetTime(20,00,00);
dt_a.SetDate(2008,8,7);
cout<<endl;
cout<<"dt_after uptate: ";
dt_a.PrintDate_Time();
return 0;
}
总结:还是有些函数在声明时没有写上你总是有点小欠缺