下载

2下载券

加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 C++课件--薛景瑄课程附录

C++课件--薛景瑄课程附录.doc

C++课件--薛景瑄课程附录

jingernanhang
2018-09-05 0人阅读 举报 0 0 0 暂无简介

简介:本文档为《C++课件--薛景瑄课程附录doc》,可适用于IT/计算机领域

附录一不同基数制十六进制十进制二进制ABCDEF附录二读取某些数据类型的最大和最小值的程序typeidrangecppTrytoreadlimitsofthetypesworking,butnotusable#include<iostreamh>#include<typeinfoh>#include"limith"copiedfrom"VCINCLUDELIMITS"withpostfixaddedtemplate<typenameT>structtyp{staticvoidrange(){cout<<typeid(T)name()<<":rangeis("cout<<std::numericlimits<T>::min()<<","cout<<std::numericlimits<T>::max()<<")"<<endl}}voidmain(){typ<char>::range()typ<bool>::range()typ<short>::range()typ<int>::range()typ(unsigned)::range()notamemberof'`globalnamespace''typ(long)::range()notamemberof'`globalnamespace''typ(float)::range()typ(double)::range()typ(longdouble)::range()}*Results:char:rangeis(C,char())bool:rangeis(,)short:rangeis(,)int:rangeis(,)*附录三ASCII码表十进制十六进制字符控制功能空NUL(笑脸)SOH•STX♥ETX♦EOT♣ENQ♠ACK•BEL(铃声)退格HTALF(LineFeed)BVT(VerticalFeed)CFF(FormFeed)DCR(CarriageReturn)ESOFSIDLEDCDCDCDCNAKSYNETBCANEMA→SUBB←ESC(escape)C└FSDGSERSFUS空格!”#$'()A*BC,DEFA:BC<D=E>FABCDEFGHIAJBKCLDMENFOPQRSTUVWXYAZBCDE^F(下划线)`abcdefghiAjBkClDmEnFopqrstuvwxyAzB{C|D}E~FDEL(delete)附录四宏定义例子macrocpp#defineSQ(x)x*x#include<iostreamh>voidmain(){inti=cout<<SQ(i)<<endli*i即先i*i再i最后icout<<i<<endl}*Results:*附录五逻辑判断语句if(j==i)和赋值及逻辑判断语句if(j=i)的区别例=and==cpp#include<iostreamh>voidmain(){inti=,j=if(j==i)cout<<i<<endlelsecout<<j<<endlif(j=i)cout<<i<<endlelsecout<<j<<endl}*Result:*例=and==cpp逻辑判断语句if(j==i)和赋值及逻辑判断语句if(j=i)的区别#include<iostreamh>voidmain(){inti=,j=if(j==i)cout<<i<<endlelsecout<<j<<endlif(j=i)cout<<i<<endl判断I是否为elsecout<<j<<endl}*Result:*附录六引用返回值用作等式左值时可能产生错误结果使用时应予注意。见下例:refercpp引用返回值不应做左值的例子#include<iostreamh>inthour=intretval(inthr)函数原型intretref(inthr)函数原型voidmain(){cout<<hour<<endl全局变量初始值retval()可用于设值cout<<hour<<endlretref()也可用于设值cout<<hour<<endlretref()=返回的变量引用用作左值时应慎重cout<<hour<<endl}intretval(inthr)返回值并非引用{hour=(hr>=hr<)hr:returnhour}intretref(inthr)返回值是引用POORPROGRAMMINGPRACTICEofreturningareferenceinthiscase{hour=(hr>=hr<)hr:returnhourDANGEROUSreferencereturn}*Results:(此例中引用返回值不应该用做左值)*附录七中央处理单元(CPU)中的主要寄存器(一)寄存器组成:CPU内的寄存器是高速存储单元可用比常用存储器高的多的速度读写数据。它们有时称为基本程序执行寄存器(basicprogramexecutionregisters)。Intel的CPU一般具有个位通用寄存器个位段寄存器一个位标志寄存器以及一个位指令寄存器。前四个通用寄存器中(generalpurposeregisters):AHALAXEAXEAX是扩展累加寄存器extendedaccumulatorregisterEBX是扩展基寄存器extendedbaseregisterECX是扩展计数寄存器extendedcountingregister和EDX是扩展数据寄存器extendeddataregister。它们可以按位使用也可按位使用还可按位使用。以EAX为例它按位使用时称为EAX按位使用时称为AX而按位使用时分别称为AH(高位)和AL(低位)。如下图所示。另四个通用寄存器中:EBP是扩展帧指针寄存器extendedframepointerregisterESP是扩展栈指针寄存器extendedstackpointerregisterESI是扩展源变址寄存器extendedsourceindexregister和EDI是扩展目的变址寄存器extendeddestinationindexregister。它们可按位或位使用。按位使用时它们分别称为BP、SP、SI和DI。(二)具体用途:EAX一般用于算术运算。在VC版本中当函数具有返回值时它还用于传送返回值给主函数(callingfunction)。ECX在循环运行时用作计数器。EBP主要用于函数调用用于访问栈上的函数参量和局部数据。一般不用于通常的算术运算或数据传递。ESP只用于堆栈运行指向栈上的数据绝不用于通常的算术运算或数据传递。ESI和EDI用于访问不同存储地址。段寄存器(segmentregisters)用于存放不同存储地址的段地址。CS用于存放程序指令的段地址SS用于存放堆栈的段地址DS用于存放数据的段地址等等。指令寄存器EIP(extendedinstructionpointerregister)用于存放下一条将要执行的程序指令的地址。标志寄存器EFLAGS或Flags(extendedflagsregister)中的各二进制位或用于控制CPU的运行或用于反映CPU的工作状态。附录八进行new操作后指向数组的指针经过delete操作后又被重新使用的例子newcppToshowthatafterapointerofanarrayisdeleted,itisagainusedforanother'new'operationofanarray#include<iostreamh>voidmain(){int*pp=newintcout<<p<<endl*p=cout<<p<<endldeletepp=newintcout<<p<<endl*p=cout<<p<<endl}*Results:xDxD*附录九自动数组与静态数组的不同状态statarrcppFromfigcppofDeitels'bookStaticarrayisinitializedtozeroautomaticallyandexistsallthetime#include<iostreamh>voidstaticArray(void)voidautoArray(void)voidmain(){cout<<"Firstcalltoeachfunction:n"staticArray()autoArray()cout<<"nnSecondcalltoeachfunction:n"staticArray()autoArray()cout<<endl}functiontodemonstrateastaticlocalarrayvoidstaticArray(void){staticintarrayinticout<<"nValuesonenteringstaticArray:n"for(i=i<i)cout<<"array"<<i<<"="<<arrayi<<""cout<<"nValuesonexitingstaticArray:n"for(i=i<i)cout<<"array"<<i<<"="<<(arrayi=)<<""}functiontodemonstrateanautomaticlocalarrayvoidautoArray(void){inti,array={,,}cout<<"nnValuesonenteringautoArray:n"for(i=i<i)cout<<"array"<<i<<"="<<arrayi<<""cout<<"nValuesonexitingautoArray:n"for(i=i<i)cout<<"array"<<i<<"="<<(arrayi=)<<""}*Results:Firstcalltoeachfunction:ValuesonenteringstaticArray:array=array=array=ValuesonexitingstaticArray:array=array=array=ValuesonenteringautoArray:array=array=array=ValuesonexitingautoArray:array=array=array=Secomdcalltoeachfunction:ValuesonenteringstaticArray:array=array=array=ValuesonexitingstaticArray:array=array=array=ValuesonenteringautoArray:array=array=array=ValuesonexitingautoArray:array=array=array=*附录十在VC下实现(连接)多文件应用程序在简捷方法中不必预先创建项目文件和工作区。按下法进行即可。此处假设共有三个文件例如:mulfiletstcpp(主文件)、mulfilecpp和mulfilecpp共三个文件。另外还有一个头文件mulfileh:()调用VC。()首先编译头文件mulfileh并且将它存到盘上本文件夹中。()接着打开并编译主文件mulfiletstcpp该程序的exe文件也将以它命名。具体操作为:①同时按“Ctrl”键和“O”键打开主文件mulfiletstcpp。②按“CtrlF”键将mulfiletstcpp进行编译。此时出现提问:“ThisbuildcommandrequiresanactiveprojectworkspaceWouldyouliketocreateadefaultprojectworkspace用户可击“是(Y)”。当显示error(s),warning(s)时表示编译完成。()再打开并编译第二文件例如mulfilecpp。具体操作为:①同时按“Ctrl”键和“O”键打开第二文件mulfilecpp。②按“CtrlF”键将mulfilecpp进行编译。此时出现提问:“mulfilecppThisfileisnotincludedintheprojectWouldyouliketoaddit用户可击“是(Y)”。当显示error(s),warning(s)时表示编译完成。()再打开并编译第三文件例如mulfilecpp。具体操作为:①同时按“Ctrl”键和“O”键打开第三文件mulfilecpp。②按“CtrlF”键将mulfilecpp进行编译。此时出现提问:“mulfilecppThisfileisnotincludedintheprojectWouldyouliketoaddit用户可击“是(Y)”。当显示error(s),warning(s)时表示编译完成。()至此所有文件都已编译完毕可以进行连接。同时按“Ctrl”键和“Tab”键直至显示主文件mulfiletstcpp。()按“F”键将mulfiletstexe进行连接。当显示error(s),warning(s)时表示连接完成。()按“CtrlF”键运行mulfiletstexe并显示运行结果。附录十一数据隐藏及代理类通过隐藏类的实现细节可以防止客户的外部程序访问类中的私有信息和私有程序逻辑。为此目的向客户提供代理类(proxyclass)代理类只能访问类的公有接口而客户不能也不必知道类的实现细节。实现代理类需要几个步骤。首先生成要隐藏私有数据的类的定义和实现文件(下例中为Implementation类)。再生成用作接口的代理类和实现文件(下例中为Interface类)。以下共四个文件隐藏头文件Fig:implementationhHeaderfileforclassImplementationclassImplementation{public:Implementation(intv){value=v}voidsetValue(intv){value=v}intgetValue()const{returnvalue}private:intvalue}头文件Fig:interfacehHeaderfileforinterfacecppclassImplementationforwardclassdeclarationclassInterface{public:Interface(int)voidsetValue(int)samepublicinterfaceasintgetValue()constclassImplementationprivate:Implementation*ptrrequirespreviousforwarddeclaration}隐藏源文件Fig:interfacecppDefinitionofclassInterface#include"interfaceh"#include"implementationh"Interface::Interface(intv):ptr(newImplementation(v)){}callImplementation'ssetValuefunctionvoidInterface::setValue(intv){ptr>setValue(v)}callImplementation'sgetValuefunctionintjnterface::getValue()const{returnptr>getValue()}客户主文件implementationcppFig:figcppHidingaclass'sprivatedatawithaproxyclasstobelinkedwithinterfaceobj#include<iostreamh>#include"interfaceh"voidmain(){Interfacei()cout<<"Implementationvalueis"<<igetValue()<<"beforesetValue()"<<endlisetValue()cout<<"Implementationvalueis"<<igetValue()<<"aftersetValue()"<<endl}*Results:ImplementationvalueisbeforesetValue()ImplementationvalueisaftersetValue()*此处使用Implementation类的同一个公有接口生成代理类的定义。代理类的唯一私有成员是Implementation类对象的指针。利用指针可以隐藏Implementation类的实现细节。而Interface类是Implementation类的代理类。注意在Interface类中提到Implementation类时只有一条指针说明即:classImplementationforwardclassdeclaration当一个类定义(如Interface类)只用另一个类(如Implementation类)的指针时另一个类的头文件不需要用#include语句包含在内而只需使用“提前类说明“(forwardclassdeclaration)将另一个类说明为一种数据类型即可。实现文件包含代理类Interface的成员函数这是唯一包含Implementation类所在头文件implementationh的文件。文件interfacecpp以预编译对象文件形式和头文件interfaceh一起提供给客户该头文件包含代理类提供服务的函数原型。而客户无法看到代理类与私有成员之间的交互操作。注意主程序中只包含Interface类的头文件而没有提到Implementation类。因此客户根本不知道Implementation类的私有数据。附录十二为数组动态分配空间时构造函数和析构函数的调用次数objarrcpp王燕书p例的扩充扩充处用红笔标出#include<iostreamh>classpoint{intx,ypublic:point(intvx=,intvy=){x=vxy=vycout<<"constructorn"}~point(){cout<<"destructorn"}voidprint(){cout<<x<<""<<y<<endl}}main(){point*pp=newpointif(!p){cout<<"allocationfailure!n"return}for(intj=i<i)piprint()deletepreturn}*Results:constructorconstructorconstructordestructordestructordestructor*附录十三§“自增和自减运算符重载”的补充例子例类的数据成员的前置自减和后置自减操作overldcppOverloadingofpredecrementalandpostdecrementaloperators#include<iostreamh>classnumber{intnumpublic:number(intn=)constructor{num=n}numberoperator()predecrementoperatornumberoperator(int)postdecrementoperatorfriendostreamoperator<<(ostream,constnumber)}Predecrementoperatoroverloadedasamemberfunctionnumbernumber::operator(){numreturn*thisreferencereturntocreateanleftvalue}PostdecrementoperatoroverloadedasamemberfunctionNotethatthedummyintegerargumentdoesnothaveanyargumentnamenumbernumber::operator(int)valuereturnnotareferencereturn{numbertemp=*thisnumreturnnondecremented,saved,temporaryobjectreturntemp}ostreamoperator<<(ostreamout,constnumbernn){cout<<nnnumreturnout}Driverforclassnumbervoidmain(){numbern(),ncout<<"nnumis"<<n<<endlcout<<"nnumis"<<n<<endl<<endlcout<<"Testingthepredecrementaloperator:n"<<"Operation:n=n"<<'n'cout<<"nnumwas"<<n<<'n'n=ncout<<"Nownnumis"<<n<<"n"cout<<"Nownnumis"<<n<<"nn"cout<<"Testingthepostdecrementaloperator:n"<<"Operation:n=n"<<'n'cout<<"nnumwas"<<n<<'n'n=ncout<<"Nownnumis"<<n<<"n"cout<<"Nownnumis"<<n<<"n"}*Results:nnumisnnumisTestingthepredecrementaloperator:Operation:n=nnnumwasNownnumisNownnumisTestingthepostdecrementaloperator:Operation:n=nnnumwasNownnumisNownnumis*附录十四§“构造函数的类型转换功能”中的补充例子具有两个形参的类型转换构造函数typeconvcppmodifiedversionoftypeconvcppToshowyoucanuseconversionconstructorwithtwoarguments#include<iostreamh>classD{doubled,fpublic:D(){d=cout<<"defaultCONS"<<endl}D(doublei){d=icout<<"initializingCONS"<<endl}D(Dobj){d=objdcout<<"copyingCONS"<<endl}D(inti,intj){typeconversionperformedd=if=jcout<<"conversionconstructor!"<<endl}~D(){cout<<"destructor"<<endl}voidPrint(){cout<<d<<','<<f<<endl}}voidmain(){Dobj(,)coutsetf(ios::showpoint)coutprecision()objPrint()}*Results:conversionconstructor!,destructor*附录十五一般程序中函数指针数组的使用funptrcppToimitatetheuseofvirtualpointerforvirtualfunctions#include<iostreamh>voidf(){cout<<"f(),"}voidg(){cout<<"g(),"}voidh(){cout<<"h()"<<endl}voidmain(){void(*ptr)()={f,g,h}函数指针数组similartoVTABLEvoid(**dblptr)()声明一个指向函数指针的指针similartodblptrdblptr=ptrordblptr=ptr将该指针初始化即将它定义为指向数组的第一个元素similartodblptr然后下面通过调用一个指针数组元素来调用相应的函数(*dblptr)()(*(dblptr))()(*(dblptr))()}*Results:f(),g(),h()*内存存储内容(栈区)ptr=ff()ptr=gptr=hg()h()存储区一定连续不一定连续附录十六不同类的不同虚地址表具有不同地址VtabaddrcppToseethattheVtablesofdifferentclasseshavethedifferentaddresses#include<iostreamh>classX{public:virtualvoidwho(){cout<<'X'<<endl}}classY:publicX{public:Y(inti){a=i}voidwho(){cout<<'Y'<<endl}inta}voidmain(){XobjxYobjy(),objy()int*ptrptr=(int*)objxcout<<hex<<*ptr<<endladdressofX::vtableptr=(int*)objycout<<hex<<*(ptr)<<endladdressofY::vtablecout<<dec<<*ptr<<endlcout<<objya<<endlptr=(int*)objyreassignpointercout<<hex<<*(ptr)<<endlsameaddressofY::vtable?cout<<dec<<*ptr<<endlcout<<objya<<endl}*Results:fc(X::Vtableindataarea)fc(anotherY::Vtable)fc(sameY::Vtable)*附录十七虚指针的补充例子补充例既有虚函数又有数据的补充例子:读出派生类对象的地址、虚指针内容(它所指向的虚地址表的地址)以及虚函数地址表内容(它所指向的虚函数的地址)。objcontvtabcppToshowthesizesoftheclassesandthestoredcontentsincludingthecontentsofVPTRandVTABLEoftheobjectsofthederivedclasseswithvirtualfunctions#include"iostreamh"classbase{intxpublic:base(inta){x=a}virtualintinc(){returnx}}classderive:base{intxpublic:derive(inta,intb):base(a){x=b}intinc(){returnx}}classgrand:derive{intxpublic:grand(inta,intb,intc):derive(a,b){x=c}intinc(){returnx}}voidmain(){cout<<"sizeofclassbaseis"<<sizeof(base)<<endlcout<<"sizeofclassderiveis"<<sizeof(derive)<<endlcout<<"sizeofclassgrandis"<<sizeof(grand)<<endlgrandgr(,,)Threeobjectsaremadetobelocatedderivedd(,)contiguouslysothatonepointer'ptr'basebs()canbeusedforallobjectscout<<"Theaddressesoftheirobjectsare:"<<endlcout<<bs<<endlcout<<dd<<endlcout<<gr<<endlbase*ptrbptrb=bsint**ptr=(int**)ptrbcout<<"Addrofobjectbs:"<<ptr<<endlcout<<"AddrofVTABLEofbs:"<<*ptr<<endlcout<<"Indexingofvirtualfunctionbsinc():"<<"x"<<hex<<**ptr<<endlptrcout<<"secondpartofbsis"<<*(ptr)<<endldec<<cout<<"Addrofobjectdd:"<<ptr<<endlcout<<"AddrofVTABLEofdd:"<<*ptr<<endlcout<<"Indexingofvirtualfunctionddinc():"<<"x"<<hex<<**ptr<<endlptrcout<<"secondpartofddis"<<*(ptr)<<endlcout<<"thirdpartofddis"<<*(ptr)<<endlcout<<"Addrofobjectgr:"<<ptr<<endlcout<<"AddrofVTABLEofgr:"<<*ptr<<endlcout<<"Indexingofvirtualfunctiongrinc():"<<"x"<<hex<<**ptr<<endlptrcout<<"secondpartofgris"<<*(ptr)<<endlcout<<"thirdpartofgris"<<*(ptr)<<endlcout<<"fourthpartofgris"<<*ptr<<endl}*Results:sizeofclassbaseissizeofclassderiveissizeofclassgrandisTheaddressesoftheirobjectsare:xFDD(栈区)xFDDC(栈区)xFDE(栈区)Addrofobjectbs:xFDD(栈区)AddrofVTABLEofbs:x(数据区)Indexingofvirtualfunctionbsinc():xa(代码区)secondpartofbsisxAddrofobjectdd:xFDDC(栈区)AddrofVTABLEofdd:xC(数据区)Indexingofvirtualfunctionddinc():x(代码区)secondpartofddisxthirdpartofddisxAddrofobjectgr:xFDE(栈区)AddrofVTABLEofgr:x(数据区)Indexingofvirtualfunctiongrinc():xb(代码区)secondpartofgrisxthirdpartofgrisxfourthpartofgrisx*DAG仍然相同对象的双区存储内容栈区数据区对象bs,共个字节对象dd,共个字节对象gr,共个字节共共占个字节其中==C和=表示三个对象内虚指针的值。其余、、、、、等表示三个对象内各个数据的值。附录十八vptrszcppToshowthesizesoftheobjectswithtwovirtualfunctions#include<iostreamh>#definePIclasscontainer{protected:doubledimensionpublic:container(doubled){dimension=d}constructorvirtualdoublesurface(){return}virtualdoublevolume(){return}}classcube:publiccontainer{public:cube(doublelength):container(length){}constructorvirtualdoublesurface(){return(*dimension*dimension)}virtualdoublevolume(){return(dimension*dimension*dimension)}}classsphere:publiccontainer{public:sphere(doubleradius):container(radius){}constructorvirtualdoublesurface(){return(*PI*dimension*dimension)}virtualdoublevolume(){return(PI*dimension*dimension*dimension*)}}voidmain(){cout<<sizeof(double)<<endlcout<<sizeof(container)<<endlcout<<sizeof(cube)<<endlcout<<sizeof(sphere)<<endl}*Results:*附录十九多个地方抛出的相同内容的异常在同一个catch程序块内处理的例子exceptioncpp*用于模拟工件加工的自动监控系统。其中手动输入温度用于模拟传感器(transducer)所测量工件温度的读取操作每个函数用于模拟对此工件加工的一道工序。经过每次函数的加工工件温度将会下降摄氏度。在加工过程中要求工件温度不能过高过低。为简化程序只在程序开始时检查温度是否过高。而在每道工序中则监测温度是否过低温度过高或过低时即抛出异常要求对工件重新处理然后再重新输入工件并测量其温度。加工完毕后程序将最后温度由摄氏度转换为华氏度并都显示。*TheappropriatetemperatureisdegConlyforteachingpurpose#include<iostreamh>#include<exception>doublectof(doublecelsius){if(celsius<)throwexception("lowerthandegCinfourthstage")cout<<"Finished!nFinaltemperatureincelsiusis:"<<celsiusreturncelsius*}doubleh(doublecelsius){if(celsius<)throwexception("lowerthandegCinthirdstage")return(ctof(celsius))}doubleg(doublecelsius){if(celsius<)throwexception("lowerthandegCinsecondstage")return(h(celsius))}doublef(doublecelsius){if(celsius<)throwexception("lowerthandegCinfirststage")return(g(celsius))}voidmain(){doublecelsius,fahrenheitboolflag=truecout<<"MeasuretemperatureinCelsius:"cin>>celsiusactuallymeasuredbytransducerwhile(flag){try{if(celsius>)throwexception("thispiecehigherthandegC")fahrenheit=f(celsius)cout<<"andinFahrenheitis:"<<fahrenheit<<endlflag=false}catch(exceptionex){exceptionhandlercout<<"Exception:"<<exwhat()<<'n'cout<<"Measuretemperatureagain:"cin>>celsius}}while}*Manykindsofresults,forexample:()MeasuretemperatureinCelsius:Finished!Finaltemperatureincelsiusis:andinFahrenheitis:()MeasuretemperatureinCelsius:Exception:lowerthandegCinfirststageMeasuretemperatureagain:Exception:lowerthandegCinsecondstageMeasuretemperatureagain:Exception:lowerthandegCinthirdstageMeasuretemperatureagain:Exception:lowerthandegCinfourthstageMeasuretemperatureagain:Finished!Finaltemperatureincelsiusis:andinFahrenheitis:*此程序中catch程序块中调用系统异常类的成员函数what()该函数用于将建立异常类对象进行初始化时的字符串显示出来例如"higherthandegC"等。请注意:以上例子只用于教学目的并无实际意义。附录二十可用于捕获各类异常的格式catch(…)例exceptioncppDifferentexceptionscaughtvaguelybyonegeneralblock#include<iostreamh>#include<mathh>#include<exception>doublequotient(doublenumerator,intdivisor){if(divisor==)throwexception("divisor")returnnumeratordivisor}voidmain(){intdivisordoublenumber,numerator,resultboolflag=truecout<<"Entertwonumbers:"cin>>number>>divisortry{if(number<)thrownumbernumerator=sqrt(number)result=quotient(numerator,divisor)cout<<"Thequotientis:"<<result<<endl}catch(){exceptionhandlercout<<"Exceptionoccured!"<<endlcout<<"Programterminated!"<<endl}}*Atleastthreekindsofresults:()Entertwonumbers:Thequotientis:()Entertwonumbers:Exceptionoccured!Programterminated!()Entertwonumbers:Exceptionoccured!Programterminated!*例exceptioncppdifferentkindsofexceptionsaretreateddifferently#include<iostreamh>#include<exception>#include<mathh>doublequotient(doublenumerator,intdivisor){if(divisor==)throwdivisorreturn(double)numeratordivisor}doubleh(doublenumerator,intdivisor){if((divisor)==)throwexception()doubleresult=quotient(numerator,divisor)returnresult}doubleg(doublenumerator,intdivisor){if((divisor)==)throwexception()doubleresult=h(numerator,divisor)returnresult}doublef(doublenumerator,intdivisor){if((divisor)==)throwexception()doubleresult=g(numerator,divisor)returnresult}voidmain(){intdivisordoublenumber,numerator,resultboolflag=truecout<<"Entertwonumbers:"cin>>number>>divisorwhile(flag){try{if(number<)thrownumbernumerator=sqrt(number)result=f(numerator,divisor)cout<<"Thequotientis:"<<result<<endlflag=false}catch(doubled){exceptionhandlercout<<"Exception:number(分子的平方值)"<<d<<"used!"<<endlcout<<"Enterapositivenumber(分子的平方值)please:"cin>>number}catch(inti){exceptionhandlercout<<"Exception:divisor(分母)"<<i<<"used!"<<endlcout<<"Enteranonzerodivisor(分母)please:"cin>>divisor}catch(){exceptionhandlercout<<"Exceptionoccured!"<<endlcout<<"Programterminated!"<<endlflag=false}}while}*Atleastthreekindsofresults:()Entertwonumbers:Thequotientis:()Entertwonumbers:Exception:number(分子的平方值)used!Enterapositivenumber(分子的平方值)please:Thequotientis:()Entertwonumbers:Exceptionoccured!Programterminated!*附录二十一当程序中同时出现clog和cout语句时的复杂情况当程序中同时出现clog和cout语句而clog和cout的语句中都是既无“flush”又无“endl”时:.首先顺序地显示最后一句clog语句之前的所有cout语句的内容而所有clog语句(包括最后一句clog语句)的内容则都顺序地写入缓存.接着显示缓存中所有clog语句的内容并清除缓存.然后顺序地显示最后一句clog语句之后的所有cout语句内容。例iocppspecialcasewhenno"endl"isused#include<iostreamh>voidmain(){inti=clog<<"ABCDE"<<'n'cout<<i<<'n'clog<<"ABCDE"<<'n'cout<<i<<'n'clog<<"ABCDE"<<'n'cout<<i<<'n'}*Results:ABCDEABCDEABCDE*附录二十二不同显示精度值的显示效果例显示小于的数值时的情况formatiocppeffectofprecision#include<iostreamh>voidmain(){doubled=cout<<d<<endldefaultprecisioniscoutprecision()cout<<d<<endlcoutprecision()cout<<d<<endlcoutprecision()cout<<d<<endl}*Results:*例显示大于的数值时的情况formatiocppeffectofprecision#include<iostreamh>voidmain(){doubled=cout<<d<<endldefaultprecisioniscoutprecision()cout<<d<<endlcoutprecision()cout<<d<<endlcoutprecision()cout<<d<<endl}*Results:ee*附录二十三使用文件流对象作为函数参数例fileoutCPPoutputtofileoutdatbyusingfilestreamobjectasargumentofafunctionwriteout()“oile”isanobjectofclassofstream#include<stdlibh>#include<fstreamh>voidwriteout(ofstreamoile,char*str){oile<<str<<endl}voidmain(){charstrifstreaminput("mydat")if(!input){cerr<<"Errorinopeningafile"<<endlexit()}charchinti=while(inputget(ch))stri=chstri=''toreplaceEOFofstreamoile("outdat")if(oilefail()){cerr<<"Errorinopeningafile"<<endlexit()}writeout(oile,str)}*Result:dataareinputfromfilemydatindirectory"jxx"andareoutputtofileoutdatcreatedindirectory"jxx"*附录二十四读取指针补充例ptrvalcppTocheckthevaluesofpointersFromLv'sbook,pwithsomestatementsadded#include<iostreamh>voidmain(){inti,*pi=i,*pidoubled,*pd=d,*pdpi=pipd=pdcout<<"指针相对值之差:"<<pipi<<','<<pdpd<<endlcout<<"地址值之差:"<<(int)pi(int)pi<<','<<(int)pd(int)pd<<endlcout<<"整数地址值:"<<pi<<','<<pi<<endlcout<<"浮点数地址值:"<<pd<<','<<pd<<endlcout<<"整型指针本身地址值:"<<pi<<','<<pi<<endlcout<<"浮点数指针本身地址值:"<<pd<<','<<pd<<endl}*Results:指针相对值之差:,地址值之差:,整数地址值:xFDF,xFDF浮点数地址值:xFDD,xFDE整型指针本身地址值:xFDEC,xFDE浮点数指针本身地址值:xFDD,xFDD*补充例ptrarrcppShowpointerarrayofcharacters#include<iostreamh>voidmain(){char*chptr={"First","Second","Third"}cout<<*chptr<<''<<*(chptr)<<''<<*(chptr)<<endlcout<<chptr<<''<<chptr<<''<<chptr<<endlchar**ptr=chptrcout<<*(ptr)<<''<<*(ptr)<<''<<*(ptr)<<endlcout<<*chptr<<''<<chptr<<endlcout<<*chptr<<''<<chptr<<endlcout<<*chptr<<''<<chptr<<endl}*Results:FirstSecondThirdFirstSecondThirdFirstSecondThirdFFSSTT*chptrchptrchptr附录二十五十六进制表示方式x中每一位所代表的值Wang’sbook,p例子中showflags()中数据的十六进制表示方式x中每一位所代表的值:低字节高字节其中i=i>>是使i右移一位每次只有一位为。只当这两个变量i和f中同一位都是时(if)的值才为否则为零。grand::inc()的调用指令:“jmpgrand::inc”grVPTR=grx=grx=grx=derive::vtablegrand::vtable即grand::inc的调用指令地址ddVPTR=Cddx=ddx=bsVPTR=bsx=base::vtabledblptrFSTiehrcisortndd

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

评分:

/39

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利