课程首页地址:http://blog.csdn.net/sxhelijian/article/details/7910565,本周题目链接:http://blog.csdn.net/sxhelijian/article/details/8953304
【项目4】日期时间类
定义一个日期类Date,数据成员包括年、月、日,SetDate(int y,int m,int d)和PrintDate()函数分别用于设置日期和显示日期;再定义一个时间类Time,数据成员包括时、分、秒,SetTime(int h,int m,int s)和PrintTime()函数分别用于设置时间和显示时间,在此基础上再定义一个日期时间类TimeDate,充分利用已有的两个类,并编写主函数测试所定义的类结构。
参考解答:
#include<iostream> using namespace std; class Date { public: void SetDate(int y,int m,int d) { Year=y; Month=m; Day=d; } void PrintDate() { cout<<Year<<"/"<<Month<<"/"<<Day<<endl; } Date():Year(0),Month(0),Day(0){} Date(int y,int m,int d):Year(y),Month(m),Day(d){} private: int Year,Month,Day; }; class Time { public: void SetTime(int h,int m,int s) { Houre=h; Minutes=m; Seconds=s; } void PrintTime() { cout<<Houre<<":"<<Minutes<<":"<<Seconds<<endl; } Time():Houre(0),Minutes(0),Seconds(0){} Time(int h,int m,int s):Houre(h),Minutes(m),Seconds(s){} private: int Houre,Minutes,Seconds; }; 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() { PrintDate(); PrintTime(); } }; int main() { TimeDate dt_a,dt_b(2010,4,16,9,30,0); dt_a.PrintDate_Time(); dt_b.PrintDate_Time(); dt_a.SetTime(20,00,00); dt_a.SetDate(2008,8,7); dt_a.PrintDate_Time(); return 0; }