• 574.50 KB
  • 2022-04-22 11:51:26 发布

《C++面向对象程序设计》习题答案.doc

  • 66页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档共5页,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
  4. 文档侵权举报电话:19940600175。
'《C++程序设计》习题解答I 目录第2部分习题解答2第1章面向对象程序设计概述2第2章面向过程程序设计12第3章类和对象14第4章继承与派生18第5章多态性与虚函数21第6章友元与静态成员25第7章运算符重载29第8章泛型编程33第9章输入/输出36第10章异常处理38I 第2部分习题解答第1章面向对象程序设计概述一、简答题简述面向过程程序设计和面向对象程序设计的编程思想,体会面向对象程序设计的优点。【答案要点】面向过程程序设计的编程思想:功能分解、逐步求精、模块化、结构化。当要设计一个目标系统时,首先从整体上概括出整个系统需要实现的功能,然后对系统的每项功能进行逐层分解,直到每项子功能都足够简单,不需要再分解为止。具体实现系统时,每项子功能对应一个模块,模块间尽量相对独立,通过模块间的调用关系或全局变量而有机地联系起来。面向对象程序设计的编程思想:(1)客观世界中的事物都是对象(object),对象之间存在一定的关系。(2)用对象的属性(attribute)描述事物的静态特征,用对象的操作(operation)描述事物的行为(动态特征)。(3)对象的属性和操作结合为一体,形成一个相对独立、不可分的实体。对象对外屏蔽其内部细节,只留下少量接口,以便与外界联系。(4)通过抽象对对象进行分类,把具有相同属性和相同操作的对象归为一类,类是这些对象的抽象描述,每个对象是其所属类的一个实例。(5)复杂的对象可以用简单的对象作为其构成部分。(6)通过在不同程度上运用抽象的原则,可以得到一般类和特殊类。特殊类继承一般类的属性与操作,从而简化系统的构造过程。(7)对象之间通过传递消息进行通信,以实现对象之间的动态联系。(8)通过关联表达类之间的静态关系。与传统的面向过程程序设计相比,面向对象程序设计的优点如下:(1)从认识论的角度看,面向对象程序设计改变了软件开发的方式。软件开发人员能够利用人类认识事物所采用的一般思维方式来进行软件开发。(2)面向对象程序中的数据的安全性高。外界只能通过对象提供的对外接口操作对象中的数据,这可以有效保护数据的安全。(3)面向对象程序设计有助于软件的维护与复用。某类对象数据结构的改变只会引起该类对象操作代码的改变,只要其对外提供的接口不发生变化,程序的其余部分就不需要做任何改动。面向对象程序设计中类的继承机制有效解决了代码复用的问题。人们可以像使用集成电路(IC)构造计算机硬件那样,比较方便地重用对象类来构造软件系统。二、编程题【程序参考代码】/*学生信息管理系统C语言源代码student.c*/#include/*包含输入/输出头文件*/#include/*包含字符串处理头文件*/#include#defineMAXSIZE100/*能够处理的学生总人数,可以随意修改*/typedefstruct{/*用于存放生日信息的结构体*/intyear;intmonth;intday;}Date;typedefstructStud{/*用于存放学生信息的结构体*/charNum[12];/*学号为11位*/charName[11];/*姓名,最多5个汉字*/charSex[2];/*性别,男记为m,女记为f*/第63页 DateBirthday;/*出生日期*/floatEnglish,DataStructure,CPlusPlus;/*三门课成绩*/floatSum,Average;/*总成绩、平均成绩*/}Student;charCurFile[40];/*存放当前正在操作的磁盘文件的文件名*/intIsOpen=0;/*当前是否有磁盘文件被打开标志*/intfound=0;/*在查找学生信息时是否找到标志*/Studentstud[MAXSIZE];/*用于存放读入内存中的所有学生信息的全局数组*/intIndex=0;/*存放实际学生人数的全局变量*//*各自定义函数原型声明*/voidCreate();/*新建学生信息文件*/voidOpen();/*打开学生信息文件,并读取学生信息到全局数组stud中*/voidDisplay();/*显示学生信息*/voidSearch();/*查询学生信息*/intSearchNum(char*Num);/*按学号查询学生信息*/intSearchName(char*Name);/*按姓名查询学生信息*/voidAppend();/*添加学生信息*/voidModify();/*修改学生信息*/voidDelete();/*删除学生信息*/voidTotal();/*统计所有学生某一科目总成绩*/voidSort();/*学生信息排序*/voidBackup();/*备份学生信息*/voidmenu()/*系统功能菜单*/{intchoice;/*用于保存用户对功能菜单的选择结果*/for(;;){/*显示系统功能菜单*/printf("n****************************************************n");printf("***************学生信息管理系统*******************n");printf("****************************************************n");printf("************1.新建学生信息文件*****************n");printf("************2.打开学生信息文件*****************n");printf("************3.显示学生信息*****************n");printf("************4.查询学生信息*****************n");printf("************5.添加学生信息*****************n");printf("************6.修改学生信息*****************n");printf("************7.删除学生信息*****************n");printf("************8.统计学生信息*****************n");printf("************9.学生信息排序*****************n");printf("************10.备份学生信息*****************n");printf("************0.退出系统*****************n");printf("****************************************************n");printf("请选择要执行的操作(0~8):_");scanf("%d",&choice);switch(choice){case1:Create();break;case2:Open();break;case3:Display();break;case4:Search();break;case5:Append();break;case6:Modify();break;case7:Delete();break;case8:Total();break;case9:Sort();break;case10:Backup();break;case0:return;第63页 default:printf("选择错误!请重新选择。n");}/*switch结束*/}/*for结束*/}voidReOrEx()/*在用户执行完一项系统功能后,可以选择:是继续运行系统,还是退出系统*/{intn;printf("n****************************************************n");printf("***************1.返回上级菜单**************n");printf("***************0.退出系统**************n");printf("****************************************************n");printf("请选择(1/0)?_");scanf("%d",&n);if(n==0){printf("n****************************************************n");printf("*************谢谢使用本系统!***************n");printf("****************************************************n");exit(1);}}voidmain(){printf("****************************************************n");printf("*********欢迎使用学生信息管理系统!*********n");printf("****************************************************n");system("pause");menu();/*系统功能以菜单的形式提供给用户*/printf("n****************************************************n");printf("*************谢谢使用本系统!***************n");printf("****************************************************n");}/*main函数结束*//*各自定义函数实现代码*/intNew(char*FileName)/*创建磁盘文件*/{FILE*fp;if((fp=fopen(FileName,"w"))==NULL){return0;}else{fclose(fp);Index=0;return1;}}voidCreate()/*新建学生信息文件*/{charFileName[40];printf("请输入新建文件的名称:");scanf("%s",&FileName);if(strcmp(FileName,"studentbackup")){strcat(FileName,".dat");if(!New(FileName))printf("%s文件创建失败!n",FileName);else{strcpy(CurFile,FileName);printf("%s文件创建成功!n",FileName);}}else{printf("%s是备份文件,禁止创建与此文件同名的文件!n",FileName);}ReOrEx();}voidOpen()/*打开学生信息文件*/{charFileName[40];printf("请输入要打开的数据文件的名称:");scanf("%s",&FileName);if(strcmp(FileName,"studentbackup")){strcat(FileName,".dat");第63页 if(IsOpen==0){FILE*fp;if((fp=fopen(FileName,"rb"))==NULL){printf("%s文件打开失败!n",FileName);}else{IsOpen=1;Index=0;while(!feof(fp)){fread(&stud[Index],sizeof(structStud),1,fp);Index++;}Index--;printf("学生总人数为:%dn",Index);fclose(fp);printf("%s文件打开成功!n",FileName);strcpy(CurFile,FileName);}}elseprintf("%s文件已经打开!n",FileName);}elseprintf("%s是备份文件,禁止打开此文件!n",FileName);ReOrEx();}voidDisplay()/*显示全部学生信息*/{inti;if(!strcmp(CurFile,"")){printf("当前并未打开或新建文件,无法显示!n");}else{printf("n显示所有学生成绩信息nn");printf("%--12s%--11s%--5s%--14s%--12s%--15s%--12s%--12s%--12sn","Num","Name","Sex","Birthday","English","DataStructure","CPlusPlus","Sum","Average");for(i=0;i=MAXSIZE){printf("错误!学生信息已满,不能添加!n");}else{printf("执行添加学生信息操作!n");printf("n请输入学生学号:");scanf("%s",Num);location=SearchNum(Num);if(!found){printf("可以进行添加操作!n");printf("n请输入学生姓名:");scanf("%s",Name);printf("n请输入学生性别:");第63页 scanf("%s",&Sex);printf("n请输入学生出生年份:");scanf("%d",&Year);printf("n请输入学生出生月份:");scanf("%d",&Month);printf("n请输入学生出生日:");scanf("%d",&Day);printf("n请输入学生英语成绩:");scanf("%f",&English);printf("n请输入学生数据结构成绩:");scanf("%f",&DataStructure);printf("n请输入学生C++成绩:");scanf("%f",&CPP);printf("n");strcpy(stud[Index].Num,Num);strcpy(stud[Index].Name,Name);strcpy(stud[Index].Sex,Sex);stud[Index].Birthday.year=Year;stud[Index].Birthday.month=Month;stud[Index].Birthday.day=Day;stud[Index].English=English;stud[Index].DataStructure=DataStructure;stud[Index].CPlusPlus=CPP;stud[Index].Sum=English+DataStructure+CPP;stud[Index].Average=stud[Index].Sum/3;Index++;printf("插入一条学生信息操作成功!n");}elseprintf("不能进行添加学生信息操作!n");}}voidSave(char*FileName)/*学生信息存盘*/{FILE*fp;inti;if((fp=fopen(FileName,"wb"))==NULL){printf("文件打开失败!");return;}for(i=0;I=1&&change;--i){change=0;for(j=0;jstud[j+1].English){strcpy(temp.Num,stud[j].Num);strcpy(temp.Name,stud[j].Name);strcpy(temp.Sex,stud[j].Sex);temp.Birthday.year=stud[j].Birthday.year;temp.Birthday.month=stud[j].Birthday.month;temp.Birthday.day=stud[j].Birthday.day;temp.English=stud[j].English;temp.DataStructure=stud[j].DataStructure;temp.CPlusPlus=stud[j].CPlusPlus;temp.Sum=stud[j].Sum;temp.Average=stud[j].Average;strcpy(stud[j].Num,stud[j+1].Num);strcpy(stud[j].Name,tud[j+1].Name);strcpy(stud[j].Sex,stud[j+1].Sex);stud[j].Birthday.year=stud[j+1].Birthday.year;stud[j].Birthday.month=stud[j+1].Birthday.month;stud[j].Birthday.day=stud[j+1].Birthday.day;stud[j].English=stud[j+1].English;stud[j].DataStructure=stud[j+1].DataStructure;stud[j].CPlusPlus=stud[j+1].CPlusPlus;stud[j].Sum=stud[j+1].Sum;stud[j].Average=stud[j+1].Average;strcpy(stud[j+1].Num,temp.Num);strcpy(stud[j+1].Name,temp.Name);strcpy(stud[j+1].Sex,temp.Sex);stud[j+1].Birthday.year=temp.Birthday.year;stud[j+1].Birthday.month=temp.Birthday.month;stud[j+1].Birthday.day=temp.Birthday.day;stud[j+1].English=temp.English;stud[j+1].DataStructure=temp.DataStructure;stud[j+1].CPlusPlus=temp.CPlusPlus;stud[j+1].Sum=temp.Sum;stud[j+1].Average=temp.Average;change=1;}第63页 }}break;case2:/*按数据结构成绩排序*/{for(i=Index-1;i>=1&&change;--i){change=0;for(j=0;jstud[j+1].DataStructure){……(此处省略的代码与按英语成绩排序中的加粗代码完全一样)}}}break;case3:/*按C++成绩排序*/{for(i=Index-1;i>=1&&change;--i){change=0;for(j=0;jstud[j+1].CPlusPlus){……(此处省略的代码与按英语成绩排序中的加粗代码完全一样)}}}break;case4:/*按总成绩排序*/{for(i=Index-1;i>=1&&change;--i){change=0;for(j=0;jstud[j+1].Sum){……(此处省略的代码与按英语成绩排序中的加粗代码完全一样)}}}break;}printf("n显示所有学生成绩信息nn");printf("%--12s%--11s%--5s%--14s%--12s%--15s%--12s%--12s%--12sn","Num","Name","Sex","Birthday","English","DataStructure","CPlusPlus","Sum","Average");for(i=0;i//包含头文件命令usingnamespacestd;//使用名字空间stdintmain(){charc;scanf("%c",&c);printf("%cn",c);cin>>c;cout<//包含头文件命令usingnamespacestd;//使用名字空间std第63页 intmain(){intc;scanf("%c",&c);printf("%cn",c);cin>>c;cout<<(char)c<//包含头文件命令usingnamespacestd;//使用名字空间stdintmain(){charc;scanf("%c",&c);printf("%dn",c);cin>>c;cout<<(int)c<//包含头文件命令usingnamespacestd;//使用名字空间stdintmain(){cout<<"sizeofintis:"<//包含头文件命令#definen8usingnamespacestd;//使用名字空间stdvoidfindmaxmin(int*p){inti,min,max;min=max=p[0];for(i=1;imax)max=p[i];if(p[i]//包含头文件命令#definen8usingnamespacestd;//使用名字空间stdtypedefintarr[n];voidfindmaxmin(arr&p){inti,min,max;min=max=p[0];for(i=1;imax)max=p[i];if(p[i]//包含头文件命令usingnamespacestd;#includeconstintN=8;voidbubble_sort(inta[],intn){//将a中整数序列按升序排序(冒泡排序)inti,j,t;for(i=n-1;i>1;i--)for(j=0;ja[j+1]){t=a[j];a[j]=a[j+1];a[j+1]=t;}}voidbubble_sort(floata[],intn){//将a中单精度浮点数序列按升序排序(冒泡排序)inti,j;floatt;for(i=n-1;i>1;i--)for(j=0;ja[j+1]){t=a[j];a[j]=a[j+1];a[j+1]=t;}}voidbubble_sort(chara[],intn){//将a中字符序列按升序排序(冒泡排序)inti,j;chart;for(i=n-1;i>1;i--)for(j=0;ja[j+1]){t=a[j];a[j]=a[j+1];a[j+1]=t;}}voidbubble_sort(stringa[],intn)第63页 {//将a中字符串序列按升序排序(冒泡排序)inti,j;stringt;for(i=n-1;i>1;i--)for(j=0;ja[j+1]){t=a[j];a[j]=a[j+1];a[j+1]=t;}}voidprint(intr[],intn){inti;for(i=0;i//包含头文件命令usingnamespacestd;//使用名字空间std#includeintmain(){strings,s1;char*ps,*pe,t;inti,j,len;cout<<"Pleaseinputastring:"<>s;s1=s;len=s1.length();for(i=0;is1[j])pe=&s1[j];}if(ps!=pe){t=*ps;*ps=*pe;*pe=t;}}cout<//包含头文件命令usingnamespacestd;//使用名字空间std#includevoidtotal(strings);intmain(){strings="fas212322@dfs3%";total(s);return0;}voidtotal(strings){intcharacters=0,digits=0,other=0;for(inti=0;i64&&s[i]<91)||(s[i]>96&&s[i]<123)){characters++;}elseif(s[i]>47&&s[i]<58){digits++;}else{other++;}}cout<<"字母个数"<//包含头文件命令usingnamespacestd;//使用名字空间stdclassBox{public:intGetLength(){returnlength;}//获取长方体的长度intGetWidth(){returnwidth;}//获取长方体的宽度intGetHeight(){returnheight;}//获取长方体的高度voidSetLength(intlength){this->length=length;}//修改长方体的长度voidSetWidth(intwidth){this->width=width;}//修改长方体的宽度第63页 voidSetHeight(intheight){this->height=height;}//修改长方体的高度intGetArea(){return2*(length*width+length*height+width*height);}//计算长方体的表面积intGetVolume(){returnlength*width*height;}//计算长方体的体积private:intlength,width,height;//长方体的长、宽、高};intmain(){Boxbox;box.SetLength(5);box.SetWidth(3);box.SetHeight(4);cout<<"Theareaofboxis:"<//包含头文件命令usingnamespacestd;//使用名字空间stdclassBox{public:Box(){length=1;width=1;height=1;}//默认构造函数Box(intlength,intwidth,intheight):length(length),width(width),height(height){}//普通构造函数intGetLength(){returnlength;}//获取长方体的长度intGetWidth(){returnwidth;}//获取长方体的宽度intGetHeight(){returnheight;}//获取长方体的高度voidSetLength(intlength){this->length=length;}//修改长方体的长度voidSetWidth(intwidth){this->width=width;}//修改长方体的宽度voidSetHeight(intheight){this->height=height;}//修改长方体的高度intGetArea(){return2*(length*width+length*height+width*height);}//计算长方体的表面积intGetVolume(){returnlength*width*height;}//计算长方体的体积private:intlength,width,height;//长方体的长、宽、高};intmain(){Boxbox1,box2(2,1,3);box1.SetLength(5);box1.SetWidth(3);box1.SetHeight(4);cout<<"Theareaofbox1is:"<//包含头文件命令usingnamespacestd;//使用名字空间stdclassBox{public:Box(){length=1;width=1;height=1;}//默认构造函数Box(intlength,intwidth,intheight):length(length),width(width),height(height){}//普通构造函数intGetLength(){returnlength;}//获取长方体的长度intGetWidth(){returnwidth;}//获取长方体的宽度intGetHeight(){returnheight;}//获取长方体的高度voidSetLength(intlength){this->length=length;}//修改长方体的长度voidSetWidth(intwidth){this->width=width;}//修改长方体的宽度第63页 voidSetHeight(intheight){this->height=height;}//修改长方体的高度intGetArea(){return2*(length*width+length*height+width*height);}//计算长方体的表面积intGetVolume(){returnlength*width*height;}//计算长方体的体积private:intlength,width,height;//长方体的长、宽、高};intmain(){Box*pBox;pBox=newBox(4,3,2);cout<<"Theareaofcubeis:"<GetArea()<usingnamespacestd;#includeclassAccount{public:Account(stringId,doubleb);//构造函数stringgetId();//获取账号doublegetBalance();//返回当前账户余额voiddeposit(doubleamount);//存款操作boolwithdraw(doubleamount);//取款操作private:stringid;doublebalance;};stringAccount::getId(){returnid;}doubleAccount::getBalance(){returnbalance;}Account::Account(stringId,doubleBalance){id=Id;balance=Balance;}voidAccount::deposit(doubleamount){balance+=amount;cout<<"存款成功!"<amount){balance-=amount;cout<<"取款成功!"<第63页 usingnamespacestd;#includeclassairCondition{public:airCondition(stringbrand,stringcolor,stringpower,boolstatus,inttemperature){this->brand=brand;this->color=color;this->power=power;this->status=status;this->temperature=temperature;}voidup(){if(status){if(temperature<30)temperature++;}}voiddown(){if(status){if(temperature<30)temperature--;}}voidshow(){if(status)cout<<"状态为:运行"<20)air.down();elseair.up();temperature=air.getTemperature();}第63页 air.show();return0;}6.【程序参考代码】#include//包含头文件命令usingnamespacestd;//使用名字空间std#includeclassStudent{public:Student(){sno="";name="";score=0;}//默认构造函数Student(stringsno,stringname,intscore):sno(sno),name(name),score(score){}//普通构造函数stringGetSno(){returnsno;}//获取学生学号stringGetName(){returnname;}//获取学生姓名intGetScore(){returnscore;}//获取学生成绩voidSetSno(stringsno){this->sno=sno;}//修改学生学号voidSetName(stringname){this->name=name;}//修改学生姓名voidSetScore(intscore){this->score=score;}//修改学生成绩voidShow()//显示学生信息{cout<<"Snois:"<80)student[i].Show();return0;}7.【程序参考代码】#include//包含头文件命令usingnamespacestd;//使用名字空间std#includeclassStudent{public:Student(){sno="";name="";score=0;}//默认构造函数Student(stringsno,stringname,intscore):sno(sno),name(name),score(score){}//普通构造函数stringGetSno(){returnsno;}//获取学生学号stringGetName(){returnname;}//获取学生姓名intGetScore(){returnscore;}//获取学生成绩voidSetSno(stringsno){this->sno=sno;}//修改学生学号voidSetName(stringname){this->name=name;}//修改学生姓名voidSetScore(intscore){this->score=score;}//修改学生成绩voidShow()//显示学生信息{cout<<"Snois:"<stud[i+1].GetScore()){flag=0;t=stud[i];stud[i]=stud[i+1];stud[i+1]=t;}if(flag==1)break;}}第63页 第4章继承与派生一、简答题1.【解】各成员在各类的范围内的访问权限如下表:类的范围f1if2jkf3mnf4p基类A公用公用保护保护私有公用派生类B公用公用保护保护不可访问公用保护私有公用派生类C公用公用保护保护不可访问公用保护不可访问公用保护(1)在main函数中能用b.i访问派生类B对象b中基类A的成员i,因为它在派生类B中是公用数据成员。不能用b.j访问派生类B对象b中基类A的成员j,因为它在派生类B中是保护数据成员,不能被类外访问。不能用b.k访问派生类B对象b中基类A的成员k,因为它是基类A的私用数据成员,只有基类A的成员函数可以访问,不能被类外访问。(2)派生类B中的成员函数能调用基类A中的成员函数f1和f2,因为f1、f2在派生类B中是公用成员和保护成员,可以被派生类的成员函数访问。(3)派生类B中的成员函数能访问基类A中的数据成员i、j,因为i,j在派生类B中是公用成员和保护成员,可以被派生类的成员函数访问。派生类B中的成员函数不能访问基类A中的数据成员k,它在派生类B中是不可访问的成员。(4)能在main函数中用c.i访问基类A的成员i,不能用c.j,c.k访问基类A的成员j,k,因为它们在派生类C中是保护成员和私有成员,不能被类外访问。也不能用c.m,c.n访问派生类B的成员m,n,因为它们在派生类C中也是保护成员和私有成员,不能被类外访问。也不能用c.p访问派生类C中的私用成员p。(5)能在main函数中用c.f1(),c.f3()和c.f4()调用f1,f3,f4成员函数,因为它们在派生类C中是公用成员函数,可以在类外被访问。不能在main函数中用c.f2()调用f2成员函数,因为它在派生类C中是保护成员函数,不能在类外被访问。(6)派生类C的成员函数f4能调用基类A中的成员函数f1,f2和派生类中的成员函数f3,因为f1、f3在派生类C中是公用成员函数,f2在派生类C中是保护成员函数,都可以被派生类C的成员函数调用。2.解:按题意没有操作,所以只列出数据成员,也不再检验#includeusingnamespacestd;classCommodity{doubleprice;//价格charname[20];//商品名charmanufacturer[20];//生产厂家intitems;//数量};classClothing:publicCommodity{//服装类chartexture[20];//材料质地};classElectric_Appliance:publicCommodity{//家电类enum{Black,White}type;//黑白家电};classVehicle:publicCommodity{//车辆类intwheel_num;//车轮数量};classShirt:publicClothing{//衬衣类enum{Formal,Casual}Style;//式样:正式、休闲};classGarment:publicClothing{//外衣类enum{Jacket,Coat}Style;//式样:夹克、外套};第63页 classHat:publicClothing{//帽子类enum{Winter,Summer,Spring_Autumn}Style;//季节风格};classShoes:publicClothing{//鞋子类enum{Winter,Summer,Spring_Autumn}Style;//季节风格};classAir_Cindition:publicElectric_Appliance{//空调boolwarm_cool;//是否冷暖floatpower;//功率};classTelevision:publicElectric_Appliance{//电视类intSize;//尺寸boolisColor;//是否彩色};classAcoustics:publicElectric_Appliance{//音响类intspeaker_num;//喇叭数目floatpower;//功率};classBicycle:publicVehicle{//自行车类intspeed_grades;//调速级数intwheel_size;//轮子大小};classCar:publicVehicle{//轿车类floatvolume;//排气量boolisSkylight;//是否有天窗intbox_num;//厢数};classMotorcycle:publicVehicle{//摩托车类floatvolume;//排气量};intmain(){return0;}二、编程题1.【程序参考代码】#includeusingnamespacestd;#includeclassCountry{public:Country(char*n,char*c,doublep){strcpy(name,n);strcpy(capital,c);population=p;}voidprint(){cout<#includeusingnamespacestd;classPerson//声明公共基类Person{public:voidset(){cin>>name>>sex>>age;}//姓名、性别、年龄的输入voiddisplay(){cout<<"name="<>teachId>>title>>wage;//工号、职称、工资的输入}voiddisplay(){Person::display();//姓名、性别、年龄的显示cout<<"tteachId="<>stuId>>stuClass>>profession>>score;//学号、班级、专业、入学成绩的输入}voiddisplay(){Person::display();//姓名、性别、年龄的显示cout<<"tstuId="<usingnamespacestd;classBuilding{public:Building(intf,intr,doublea){floors=f;rooms=r;area=a;}protected:intfloors;introoms;doublearea;};classTeachBuilding:publicBuilding{public:TeachBuilding(intf,intr,doublea,intcr):Building(f,r,a){classrooms=cr;}voidshow(){cout<<"floors="<#includeusingnamespacestd;classCar{protected:string_model;int_color;unsignedint_motopower;第63页 unsignedint_speed;unsignedint_weight;unsignedint_id;public:voidshow();};classBus:publicCar{private:unsignedint_seatnum;string_corp;public:voidshow();Bus(stringmodel,intcolor,unsignedintmotopower,unsignedintspeed,unsignedintweight,unsignedintid,unsignedintseatnum,stringcorp){_model=model;_color=color;_motopower=motopower;_speed=speed;_weight=weight;_id=id;_seatnum=seatnum;_corp=corp;}};classTruck:publicCar{private:unsignedint_load;string_corp;public:voidshow();Truck(stringmodel,intcolor,unsignedintmotopower,unsignedintspeed,unsignedintweight,unsignedintid,unsignedintload,stringcorp){_model=model;_color=color;_motopower=motopower;_speed=speed;_weight=weight;_id=id;_load=load;_corp=corp;}};voidCar::show(){cout<<"型号:"<<_model<show();cout<<"============="<show();system("pause");return0;}5.【程序参考代码】#includeusingnamespacestd;#includeclassCircle{public:Circle(doubler){radius=r;}doubleget_area(){return3.1416*radius*radius;}private:doubleradius;};classTable{public:Table(doubleh){height=h;}doubleget_height(){returnheight;}private:doubleheight;};classRoundTable:publicTable,publicCircle{char*color;public:RoundTable(doubleh,doubler,charc[]):Table(h),Circle(r){color=newchar[strlen(c)+1];strcpy(color,c);}char*get_color(){returncolor;}};intmain(){RoundTablert(0.8,1.0,"白色");cout<<"圆桌的高:"<#includeusingnamespacestd;classCar{public:Car(stringmodel,intcolor,unsignedintmotopower,unsignedintspeed,unsignedintweight,unsignedintid){_model=model;_color=color;_motopower=motopower;第63页 _speed=speed;_weight=weight;_id=id;}voidshow();private:string_model;int_color;unsignedint_motopower;unsignedint_speed;unsignedint_weight;unsignedint_id;};classBus:virtualpublicCar{public:Bus(stringmodel,intcolor,unsignedintmotopower,unsignedintspeed,unsignedintweight,unsignedintid,unsignedintseatnum,stringcorp):Car(model,color,motopower,speed,weight,id){_seatnum=seatnum;_corp=corp;}voiddisplay();protected:unsignedint_seatnum;string_corp;};classWagon:virtualpublicCar{public:Wagon(stringmodel,intcolor,unsignedintmotopower,unsignedintspeed,unsignedintweight,unsignedintid,unsignedintload,stringcorp):Car(model,color,motopower,speed,weight,id){_load=load;_corp=corp;}voiddisplay();protected:unsignedint_load;string_corp;};classStationWagon:publicBus,publicWagon{public:StationWagon(stringmodel,intcolor,unsignedintmotopower,unsignedintspeed,unsignedintweight,unsignedintid,unsignedintseatnum,unsignedintload,stringcorp):Car(model,color,motopower,speed,weight,id),Bus(model,color,motopower,speed,weight,id,seatnum,corp),Wagon(model,color,motopower,speed,weight,id,load,corp){}voiddisplay();};voidCar::show(){cout<<"型号:"<<_model<#includeusingnamespacestd;classDate{public:Date(){year=0;month=0;day=0;}//无参构造函数Date(intmm,intdd,intyy){year=yy;month=mm;day=dd;}//带参数的构造函数Date(constDate&d){year=d.year;month=d.month;day=d.day;}//复制构造函数voidsetDate(constint,constint,constint);//修改日期的函数voiddisplay();//输出日期的函数intgetYear();//获取年份的函数intgetMonth();//获取月份的函数intgetDay();//获取日信息的函数private:intyear,month,day;};//设置成员变量,mm:月份;dd:天数;yy:年份;voidDate::setDate(constintmm,constintdd,constintyy){year=yy;month=mm;day=dd;}voidDate::display(){cout<#includeusingnamespacestd;classbase{public:voidsettitle(){cout<<"书名:";cin>>title;}voidprinttitle(){cout<<"书名:"<>numsold;}boolisgood(){return(numsold>500)?true:false;}private:intnumsold;//月销售书量};第63页 classJournal:publicbase{public:voidsetsold(){cout<<"每月销售杂志量:";cin>>numsold;}boolisgood(){return(numsold>2500)?true:false;}private:intnumsold;//月销售杂志量};intmain(){base*p[50];Book*pbook;Journal*pjour;charch;intcount=0;do{cout<<"输入书(b)或杂志(j):";cin>>ch;if(ch=="b"){pbook=newBook;pbook->settitle();pbook->setsold();p[count++]=pbook;}elseif(ch=="j"){pjour=newJournal;pjour->settitle();pjour->setsold();p[count++]=pjour;}elsecout<<"输入错误"<>ch;}while(ch=="y");for(inti=0;iprinttitle();if(p[i]->isgood())cout<<"销售良好!"<#includeusingnamespacestd;classemployee//虚基类{public:employee(){cout<<"职工编号:";cin>>ID;cout<<"职工姓名:";第63页 cin>>name;salary=0;//月薪};virtualvoidpay()=0;//月薪计算函数virtualvoidshow()=0;protected:stringname;//姓名intID;//职工号doublesalary;//月薪};classtechnician:virtualpublicemployee{public:technician(){perhour=20;}//每小时附加酬金voidpay(){cout<<"请输入技术人员本月工作时数:n";cin>>hours;salary=perhour*hours;}voidshow(){cout<<"技术人员"<>amount;salary=amount*slfactor;}voidshow(){cout<<"销售员"<>amount;salary=monthpay+amount*slfactor;第63页 }voidshow(){cout<<"销售经理"<pay();p->show();p=&tec1;p->pay();p->show();p=&sal1;p->pay();p->show();p=&sam1;p->pay();p->show();return0;}第63页 第6章友元与静态成员一、程序分析题1.程序执行结果:30【程序执行结果分析】在main()函数中,定义两个Sample类对象s1和s2,其私有数据成员的值分别为10和20,然后调用add函数求这两个对象的私有数据成员的和,结果为30。2.程序执行结果:2【程序执行结果分析】在main()函数中,定义B类对象b,然后调用该对象的set函数,在set函数中,定义A类对象a,并把a对象的数据成员的值设置为2并进行输出,结果为2。二、编程题1.【程序参考代码】#includeusingnamespacestd;#includeclassDate{public:Date(inty=2008,intm=8,intd=8);Date(Date&d);voidSetDate(inty,intm,intd);friendvoidprint(Date&d);private:intyear,month,day;};Date::Date(inty,intm,intd){year=y;month=m;day=d;}Date::Date(Date&d){year=d.year;month=d.month;day=d.day;}voidDate::SetDate(inty,intm,intd){year=y;month=m;day=d;}voidprint(Date&d){cout<<"日期对象的具体信息为:";cout<usingnamespacestd;classBBank;//这里预先引用声明,类BBank在后面声明classGBank;//这里预先引用声明,类GBank在后面声明classCBank//声明中国银行类CBank{public:CBank(){balance=0;}//构造函数CBank(intb){balance=b;}//重载构造函数voidsetbalance(){第63页 cout<<"输入中国银行存款:";cin>>balance;}voiddisplay(){cout<<"中国银行存款数:"<>balance;}voiddisplay(){cout<<"工商银行存款数:"<>balance;}voiddisplay(){cout<<"农业银行存款数:"<第63页 usingnamespacestd;classScore{public:Score(intx){score=x;sum+=x;}intgetscore(){returnscore;}staticintgetsum(){returnsum;}private:intscore;//成绩staticintsum;//总分};intScore::sum=0;intmain(){Score*p;ints,count=1;cout<<"输入一个班的学生成绩直到输入-1为止!"<>s;if(s==-1)break;p=newScore(s);deletep;count++;}count--;cout<<"总分"<usingnamespacestd;classAccount{public:Account(char*Name,char*Psw);Account(){number++;}~Account(){number--;}intgetNumber(){returnnumber;}private:charname[10];charpsw[6];staticintnumber;//保存对象个数};Account::Account(char*Name,char*Psw){strcpy(name,Name);strcpy(psw,Psw);number++;}intAccount::number=0;//将静态成员初始化为0intmain(){Accountza("tom","123456");cout<usingnamespacestd;classComplex{public:Complex(){real=0;imag=0;}Complex(doubler,doublei){real=r;imag=i;}Complexoperator+(Complex&c2);Complexoperator-(Complex&c2);voiddisplay();private:doublereal;doubleimag;};voidComplex::display(){cout<<"("<classComplex{public:Complex(){real=0;imag=0;}Complex(doubler,doublei){real=r;imag=i;}第63页 friendComplexoperator+(Complex&c1,Complex&c2);friendComplexoperator-(Complex&c1,Complex&c2);voiddisplay();private:doublereal;doubleimag;};voidComplex::display(){cout<<"("<usingnamespacestd;classComplex{public:Complex(){real=0;imag=0;}Complex(doubler,doublei){real=r;imag=i;}doubleget_real();doubleget_imag();voiddisplay();private:doublereal;doubleimag;};doubleComplex::get_real(){returnreal;}doubleComplex::get_imag(){returnimag;}voidComplex::display(){cout<<"("<classMatrix//定义Matrix类{public:Matrix();//默认构造函数friendMatrixoperator+(Matrix&,Matrix&);//重载运算符“+”voidinput();//输入数据函数voiddisplay();//输出数据函数private:intmat[2][3];};Matrix::Matrix()//定义构造函数{for(inti=0;i<2;i++)for(intj=0;j<3;j++)mat[i][j]=0;}Matrixoperator+(Matrix&a,Matrix&b)//定义重载运算符“+”函数{Matrixc;for(inti=0;i<2;i++)for(intj=0;j<3;j++){c.mat[i][j]=a.mat[i][j]+b.mat[i][j];}returnc;}voidMatrix::input()//定义输入数据函数{cout<<"inputvalueofmatrix:"<>mat[i][j];}voidMatrix::display()//定义输出数据函数{for(inti=0;i<2;i++){for(intj=0;j<3;j++){cout<第63页 classComplex{public:Complex(){real=0;imag=0;}Complex(doubler){real=r;imag=0;}Complex(doubler,doublei){real=r;imag=i;}friendComplexoperator+(Complexc1,Complexc2);voiddisplay();private:doublereal;doubleimag;};Complexoperator+(Complexc1,Complexc2){returnComplex(c1.real+c2.real,c1.imag+c2.imag);}voidComplex::display(){cout<<"("<usingnamespacestd;classComplex{public:Complex(){real=0;imag=0;}Complex(doubler){real=r;imag=0;}Complex(doubler,doublei){real=r;imag=i;}operatordouble(){returnreal;}voiddisplay();private:doublereal;doubleimag;};voidComplex::display(){cout<<"("<usingnamespacestd;classDate{public:Date(){year=0;month=0;day=0;}//默认构造函数第63页 Date(intx,inty,intz){year=x;month=y;day=z;}//重载构造函数Dateoperator+(intm);//加天数Dateoperator-(intm);//减天数intoperator-(Date&q);//日期差friendostream&operator<<(ostream&out,Date&t);private:intyear,month,day;intleap(inty);};intDate::leap(inty){if((y%100==0&&y%400==0)||(y%100!=0&&y%4==0))return1;elsereturn0;}DateDate::operator+(intm){Datet(*this);intd[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}},temp,f;//d为12个月每个月天数的数组f=leap(year);temp=m;if(d[f][month-1]-t.day>=temp){t.day=t.day+temp;}else{temp=temp-(d[f][t.month-1]-t.day);t.month++;if(t.month==12){t.month=1;t.year++;}while(temp>=d[f][t.month-1]){temp=temp-d[f][t.month-1];t.month++;if(t.month==13){t.month=1;t.year++;}}t.day=temp;}returnt;}DateDate::operator-(intm){Datet(*this);intd[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}},f,temp;f=leap(year);temp=m;if(t.day>temp){t.day=t.day-temp;}else{第63页 temp=temp-t.day;t.month--;if(t.month==0){t.month=12;t.year--;}t.day=d[f][month-1];while(temp>=d[f][t.month-1]){temp=temp-d[f][t.month-1];t.month--;if(t.month==0){t.month=12;t.year--;}t.day=d[f][month-1];}t.day=d[f][t.month-1]-temp;}returnt;}intDate::operator-(Date&q){intdif=0;intd[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}},y,m=0,i,f;Datet1(*this),t2(q),temp;if(year>q.year){temp=t1;t1=t2;t2=temp;}elseif(year==q.year&&month>q.month){temp=t1;t1=t2;t2=temp;}elseif(year==q.year&&month==q.month&&day>q.day){temp=t1;t1=t2;t2=temp;}if(t1.year==t2.year){if(t1.month==t2.month){dif=t2.day-t1.day;}else{f=leap(t1.year);dif+=d[f][t1.month-1]-t1.day;for(i=t1.month;iusingnamespacestd;classTimer{public:Timer();Timer(inth,intm,ints);intOver();friendTimeroperator--(Timer&t);friendostream&operator<<(ostream&out,Timer&t);friendistream&operator>>(istream&in,Timer&t);private:inthours;intminutes;intseconds;第63页 };Timer::Timer(){hours=minutes=seconds=0;}Timer::Timer(inth,intm,ints){hours=h;minutes=m;seconds=s;}intTimer::Over(){if(seconds==0&&minutes==0&&hours==0)return1;elsereturn0;}Timeroperator--(Timer&t){if(t.seconds==0){t.seconds=59;if(t.minutes==0&&t.hours==0){returnt;}elseif(t.hours!=0&&t.minutes==0){t.minutes=59;t.hours--;}elset.minutes--;}elset.seconds--;returnt;}ostream&operator<<(ostream&out,Timer&t){out<>(istream&in,Timer&t){cout<<"Inputhours:";in>>t.hours;cout<<"Inputminutes:";in>>t.minutes;cout<<"Inputseconds:";in>>t.seconds;returnin;}intmain(){Timert;cin>>t;cout<<"t="<#includeusingnamespacestd;templateTmax(Ta[],intn){Ttemp=a[0];for(inti=1;i#includeusingnamespacestd;templatevoidsort(Ta[],intn)//改进的冒泡排序{inti,j;Tt;intflag;for(j=0;ja[i+1]){flag=0;t=a[i];a[i]=a[i+1];a[i+1]=t;}if(flag==1)break;}}intmain()第63页 {inta[5]={1,9,0,23,-45};stringb[5]={"Morning","Good","Best","Perfect",""Student"};sort(a,5);cout<<"排序后的a数组为:"<//#includeusingnamespacestd;templateclassList{protected:structNode{Node*pNext;T*pT;};Node*pFirst;public:List(){pFirst=0;}voidAdd(T&t){Node*temp=newNode;temp->pT=&t;temp->pNext=pFirst;pFirst=temp;}voidRemove(T&t){Node*temp=0;if(*(pFirst->pT)==t){temp=pFirst;pFirst=pFirst->pNext;}else{for(Node*p=pFirst;p->pNext;p=p->pNext)if(*(p->pNext->pT)==t){temp=p->pNext;p->pNext=temp->pNext;break;}}if(temp){deletetemp->pT;deletetemp;}}第63页 T*Find(T&t){for(Node*p=pFirst;p->pNext;p=p->pNext){if(*(p->pT)==t)returnp->pT;}return0;}voidPrintlist(){for(Node*p=pFirst;p->pNext;p=p->pNext)cout<<*(p->pT)<<"";cout<pNext;deletep->pT;deletep;}}};intmain(){Listfloatlist;for(inti=1;i<7;i++)floatlist.Add(*newfloat(i+0.6));floatlist.Printlist();floatb=3.6;float*pa=floatlist.Find(b);if(pa)floatlist.Remove(*pa);floatlist.Printlist();return0;}4.【程序参考代码】#include#include#include#includeusingnamespacestd;templateclassQueue{private:intfront,rear;T*element;intmaxsize;public:Queue(intn=10000);~Queue(){delete[]element;}voidpush_back(Titem);Tpop_front();Tget_front();voidclear(){front=rear=0;}第63页 boolisempty(){returnfront==rear;}boolisfull(){return(rear+1)%maxsize==front;}intlength(){return(rear-front+maxsize)%maxsize;}};templateQueue::Queue(intn=10000){front=0;rear=0;maxsize=n;element=newT[maxsize];}templatevoidQueue::push_back(Titem){assert(!isfull());rear=(rear+1)%maxsize;element[rear]=item;}templateTQueue::pop_front(){assert(!isempty());front=(front+1)%maxsize;returnelement[front];}templateTQueue::get_front(){assert(!isempty());returnelement[(front+1)%maxsize];}intmain(){Queuetest(10);inti;for(i=1;i<=9;i++)test.push_back(i);for(i=1;i<=9;i++)cout<#include#include//为了使用vector容器#include//为了使用sort算法#include//为了使用输入输出迭代器usingnamespacestd;#include#includeintmain(void){第63页 typedefvectorIntVector;typedefistream_iteratorIstreamItr;typedefostream_iteratorOstreamItr;typedefback_insert_iteratorBackInsItr;IntVectornum;//构造空向量numsrand(time(0));inttemp;for(inti=0;i<10;i++){temp=rand()%100+1;num.push_back(temp);//在向量v的尾部插入元素}for(i=0;i<10;i++)cout<>”输入字符串举例:stringS;cin>>S;(2)用成员函数getline()函数输入一个字符串,该函数使用格式如下:cin.getline(char*buf,intlimit,chardeline="n");举例:constintS=10;charbuf[S]="";cout<<"Input…n";cin.getline(buf,S);(3)用成员函数read()输入一个字符串使用成员函数read()可以从输入流中读取指定数目的字符并将它们存放在指定的数组中。该函数使用格式如下:cin.read(char*buf,intsize);其中,buf是用来存放读取来的字符的字符指针或者是字符数组,size是一个int型数,用来指定从输入流中读取字符的个数。举例:constintS=10;charbuf[S]="";cout<<"Input…n";cin.read(buf,S);5.答:文本文件中每个字节存一个ASCII码,表示一个字符。二进制文件是把内存中的存储形式原样写到外存中。对文本文件的读写操作可以用流插入运算符“<<”和流提取运算符“>>”输入∕输出标准类型的数据,也可以用文件流的put、get、getline等成员函数进行字符的输入∕输出。对二进制文件的读操作可以用文件流的成员函数read,配合文件流的成员函数seekg可以随机读取二进制文件。对二进制文件的写操作可以用文件流的成员函数write,配合文件流的成员函数seekp可以随机写数据到二进制文件。使用文本文件来保存数据,操作简单,但谁都可以读取这些数据,无保密性。并且占用的存储空间较大。使用二进制文件,可以控制字节长度,读写数据时不会出现二义性,可靠性高。同时不知格式是无法读取的,保密性好。文件结束后,系统不会再读,但程序不会自动停下来,所以要判断文件中是否已没有数据。使用起来可以节省外存空间和转换时间,但是它的一个字节不对应一个字符。6.答:在C++中可以由程序来实现文件指针的移动,从而实现文件的随机访问,即可读写流中任意一段内容。一般文本文件很难准确定位,所以随机访问多用于二进制文件。第63页 二、编程题1.【程序参考代码】#includeusingnamespacestd;#includeusingnamespacestd;#includeintmain(){doublea,b,c;doubledisc;cout<<"PleaseEntera,b,c:";cin>>a>>b>>c;if(a==0)cerr<<"二次项系数a的值不能为0!"<>fnum1;//输入3.1415926535  cout<usingnamespacestd;#include#include#includeconstintn=100;intmain(){ofstreamofile;ifstreamifile;inta[n],i,j;charch,b[256];for(i=0;i>ch;if(ch=="y"||ch=="Y"){ifile.open("prime.txt");i=0;while(ifile.get(b[i])){//读标题,不可用>>,它不能读白字符,if(b[i]=="n")break;第63页 i++;}b[i]="";cout.flags(ios::left);cout<>i;//由文件读入if(ifile.eof()!=0)break;cout<>ch;if(ch=="y"||ch=="Y"){ifile.clear(0);ifile.open("prime.dat",ios::in|ios::binary);if(!ifile){cout<<"文件打开失败!"<>ch;if(ch=="y"||ch=="Y"){ifile.clear(0);ifile.open("prime.dat",ios::in|ios::binary);count=0;while(1){ifile.read((char*)&i,sizeof(int));if(ifile.eof()!=0)break;count++;}ifile.clear(0);//当文件读完时,eofbit=1,不清0,后面的操作不能进行ifile.seekg(-4,ios::end);for(j=1;j<=count;j++){ifile.read((char*)&i,sizeof(int));cout<#include#includeusingnamespacestd;structperson{charnum[4];charname[20];charsex;intage;floatscore;};intmain(){personstud[10]={"001","Zhangsan","m",18,90,"002","Lisi","f",19,80,"003","Wangwu","f",18,98,"004","Zhaoliu","m",18,68,"005","Tianqi","f",19,77,"006","Liuba","m",18,87,"007","Gaojiu","m",18,86,"008","Qishan","f",17,95,"009","Baohao","m",18,93,"010","Maoyu","m",18,88};fstreamoutfile("student.dat",ios::out|ios::binary);if(!outfile){cerr<<"openerror!"<#includeusingnamespacestd;intmain(){doubletriangle(double,double,double);doublea,b,c;cin>>a>>b>>c;try//在try块中包含要检查的函数{cout<0&&b>0&&c>0)if(a+b>c&&b+c>a&&c+a>b){doubles=(a+b+c)/2;returnsqrt(s*(s-a)*(s-b)*(s-c));}elsethrow"Itisn"tatriangle!";//当不符合三角形条件抛出异常信息elsethrow"Itisn"tatriangle!";}2.【程序参考代码】#includeusingnamespacestd;constintMAX=3;classFull{};//堆栈满时抛出的异常类classEmpty{};//堆栈空时抛出的异常类classStack{private:ints[MAX];inttop;public:Stack(){top=-1;}voidpush(inta);intpop();};voidStack::push(inta){if(top>=MAX-1)throwFull();s[++top]=a;}intStack::pop(){if(top<0)throwEmpty();returns[top--];}intmain(){Stacks;try{s.push(10);s.push(20);s.push(30);//s.push(40);//将产生栈满异常cout<<"stack(0)="<#includeusingnamespacestd;intmain(){/*//创建a.txt/ofstreamoutput1;output1.open("a.txt");//openthefileif(output1.fail())//打开文件失败则退出{cout<<"Filedoesnotexist"<