资源描述:
《实验3 继承和派生类的应用》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、实验3继承和派生类的应用实验3继承和派生类的应用3.1实验目的1.掌握多重继承和派生类的方法2.掌握初始化基类成员的方法3.掌握定义虚基类的方法3.2实验内容与步骤1.上机实验题一定义一个日期(年、月、日)的类和一个时间(时、分、秒)的类,并由这两个类派生出日期和时间类。主函数完成基类和派生类的测试工作。⑴分析定义一个描述日期的类,构造函数完成年、月、日的初始化,包含一个重新设置日期的成员函数,一个获取日期的成员函数。该类可定义为:classDate{intYear,Month,Day;//分别存放年、月、日public:Date(in
2、ty=0,intm=0,intd=0){Year=y;Month=m;Day=d;}voidSetDate(int,int,int);voidGetDate(char*);};函数SetDate完成数据成员的赋初值。函数GetDate要将整数年、月、日变换成字符串后,存放到参数所指向的字符串中。把一个整数变换成字符串可通过库函数:char*_itoa(inta,char*s,intb);来实现,参数a为要变换的整数,b为数制的基数(如10,表示将a转换为对应的十进制的字符串),转换的结果存放到s所指向的字符串中。函数返回变换后字符串的首
3、指针。该成员函数可以是:voidDate::GetDate(char*s){chart[20];实验3继承和派生类的应用_itoa(Year,s,10);//将年变换为字符串表示strcat(s,"/");//年、月、日之间用“/”隔开_itoa(Month,t,10);//将月变换为字符串表示strcat(s,t);//将年、月字符串拼接strcat(s,"/");_itoa(Day,t,10);strcat(s,t);//将年、月、日拼接成一个字符串}定义描述时间的类与描述日期的类类同,然后用这二个类作为基类,公有派生出描述日期和时
4、间的类。简化的参考程序如下:#include#include#includeclassDate{intYear,Month,Day;//分别存放年、月、日public:Date(inty=0,intm=0,intd=0){Year=y;Month=m;Day=d;}voidSetDate(int,int,int);voidGetDate(char*);};voidDate::SetDate(inty,intm,intd){Year=y;Month=m;Day=d;}void
5、Date::GetDate(char*s){chart[20];_itoa(Year,s,10);strcat(s,"/");_itoa(Month,t,10);strcat(s,t);strcat(s,"/");_itoa(Day,t,10);strcat(s,t);}classTime{intHours,Minutes,Seconds;//时、分、秒public:Time(inth=0,intm=0,ints=0)实验3继承和派生类的应用{Hours=h;Minutes=m;Seconds=s;}voidSetTime(inth,i
6、ntm,ints){Hours=h;Minutes=m;Seconds=s;}voidGetTime(char*);};voidTime::GetTime(char*s){chart[20];_itoa(Hours,s,10);strcat(s,":");_itoa(Minutes,t,10);strcat(s,t);strcat(s,":");_itoa(Seconds,t,10);strcat(s,t);}classDateTime:publicDate,publicTime{//公有派生public:DateTime():Date
7、(),Time(){}DateTime(inty,intm,intd,inth,intmin,ints):Date(y,m,d),Time(h,min,s){}voidGetDateTime(char*);voidSetDateTime(inty,intm,intd,inth,intmin,ints);};voidDateTime::GetDateTime(char*s){chars1[100],s2[100];GetDate(s1);GetTime(s2);strcpy(s,"日期和时间分别是:");strcat(s,s1);strc
8、at(s,";");strcat(s,s2);}voidDateTime::SetDateTime(inty,intm,intd,inth,intmin,ints){SetDate(y,m,d);SetTi