头文件代码
程序代码:
class Time{
private:
int hour;
int minute;
int second;
public:
Time (const int& nHour,
const int& nMinute,
const int& nSecond);
Time ();
void disp();
};
class DateTime: public Time{
private:
int year;
int month;
int day;
public:
DateTime (const int& nYear,
const int& nMonth,
const int& nDay,
const int& nHour,
const int& nMinute,
const int& nSecond);
DateTime();
void disp();
void set (const int& nYear,
const int& nMonth,
const int& nDay,
const int& nHour,
const int& nMinute,
const int& nSecond);
};
类成员函数实现代码
程序代码:
Time::Time (const int& nHour,
const int& nMinute,
const int& nSecond)
{
hour = nHour;
minute = nMinute;
second = nSecond;
}
Time::Time()
{
hour = 0;
minute = 0;
second = 0;
}
void Time::disp()
{
cout<<hour<<" Hour(s)"<<endl;
cout<<minute<<" Minute(s)"<<endl;
cout<<second<<" Second(s)"<<endl;
}
DateTime::DateTime (const int& nYear,
const int& nMonth,
const int& nDay,
const int& nHour,
const int& nMinute,
const int& nSecond)
{
Time(nHour,nMinute,nSecond);
day = nDay;
month = nMonth;
year = nYear;
}
DateTime::DateTime()
{
Time();
year = 0;
month = 0;
day = 0;
}
void DateTime::disp()
{
cout<<year<<" Year(s)"<<endl;
cout<<month<<" Month(s)"<<endl;
cout<<day<<" Day(s)"<<endl;
Time::disp();
}
void DateTime::set (const int& nYear,
const int& nMonth,
const int& nDay,
const int& nHour,
const int& nMinute,
const int& nSecond)
{
Time::Time(nHour,nMinute,nSecond);
day = nDay;
month = nMonth;
year = nYear;
}
这里只给出继承类的构造方法。组合类的构造方法请自行完成。
如果加上对时间/日期是否逾界的代码,类的定义就更完善了。