C++面向對象高效編程-源碼_第1頁
C++面向對象高效編程-源碼_第2頁
C++面向對象高效編程-源碼_第3頁
C++面向對象高效編程-源碼_第4頁
已閱讀5頁,還剩122頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

2012-11-8->2012/11/12///////////////////////////////////////////////////第1章什么是面向對象編程///////////////////////////////////////////////////JustaplainbankaccountrecordstructAccount{char*name/*nameofaccountholder*/AccountNumaccountId;/*andmanyotherdetails*/floatbalance;floatinterestYTD;/*yeartodatainterest*/characcountType;/*SavingsrChecking,Loanetc*/)AccountNumCreateNewAccount(constcharname[],chartypeOfAccount);//classBankAccountclassBankAccount{public://ManydetailsomittedforsimplicityvoidMakeDeposit(floatamount);floatwithDraw();boolTransfer(BankAccount&to,floatamount);floatGetBalance()const;private://ImplementationdatafortheprivateuseoftheBankAccountclassfloatbalance;floatinteresteYTD;char*owner;intaccount_number;);//ImplementationofanoperationofclassBankAccountvoidBankAccount::MakeDeposit(floatamount){if(amount>0.0)balance=balance+amount;)///:~//ClassCardenumSuit{Clubs,Diamond,Heart,Spade,Unknown};enumRank{Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace,Invalid};enumColor{Red,Black};classCard{public:voidFaceUp();//ShowcardfaceupvoidFaceDown();//Makeitfacedown//AndmanyothermemberfunctionsCard(Rankr,Suits);//Createacardwiththesespecificationsprivate:RankcardRank;SuitcardSuit;ColorcardColor;};///:~classNumber{public:NumberSqrt();NumberPower(NumberraiseTo);NumberInverse();NumberAbsolute();//absolutevalueofthenumberprivate://Usesomeinternalrepresentationtostorethenumber};///////////////////////////////////////////////////第2章什么是數(shù)據(jù)抽象/////////////////////////////////////////////////typedefStack*Stackld;typedefintbool;structStack{int*data;/*storageforelementsonthestack*/unsignedcount;/*numberofelementsonthestack*/int*top;/*pointertotopofstack*//*andmore????/};classTint{public://Constructor:CreateaTintfromanintTint(intvalue);Tint(longmostSignificant,unsignedlongleastsignificant);//CreateaTintfromalonginteger:Tint(longvalue);//CreateaTintfromashortinteger:Tint(shortvalue)

//DefaultConstructor:Tint();//Copyconstructor:Tint(constTInt©);//AssignmentOperatorTInt&operator=(constTint&assign);//Destructor//OperatorsfortheTinttypeTintoperator+(constTint&Tintoperator-(constTint&Tintoperator+(constTint&Tintoperator-(constTint&operand)const;//additionoperand)const;//subtractionTintTintTintoperator*(constoperator/(constoperator%(constTInt&multiplicand)const;//multiplicationTintTintTintoperator*(constoperator/(constoperator%(constTInt&multiplicand)const;//multiplicationTint*divideBy)const;//divisionTInt&divedeBy)const;//modulodivision//AddoperandtothisnumberTintoperator+=(consetTintsopeand);//Manyotheroperatorsomittedforsimplicity...//RaisethisTintnumbertothepower1toTintper(constTintsto)const;voidPrint()const;//ReturntheabsolutevalueofthisTintTintAbsolute()const;//ChangesignofthisnumbervoidFlipSign();//HelperfunctionslongGetMostSignificantPart()const;unsignedlongGetLeastSignificantPart()const;private://InternalrepresentationoftheTinttypeunsignedlong__leastSignificantPart;long_mostSignificantPart;//andprobablysomeprivatememberfunctionstootypedefshortErrorCode;classTLaserDiscPlayer{public://OperationsErrorCodeErrorCodeErrorCodeErrorCodeErrorCodePlay(unsignedatChapter=0);Stop(void);SearchFor(unsignedchapter);OpenTray();CloseTray();voidPowerOn();voidPowerOff();ErrorCodePause();//ConstructorTLaserDiscPlayer();//Destructor**TLaserDiscPlayer();//andmanymoreprivate:enumETrayStatus{eClosed,eOpen};enumEPowerStatus{eOffzeOn};enumEPlayerMode{ePlay,eSearch,ePause,eStop};ETrayStatus_trayStatus;//openorclosedEPowerStatus_powerStatus;//OnorOffEPlayerMode_playerMode;//Playing,searchingetc.//andmanymore};//Implementationofoperator+TintTint::operator+(constTint&operand)const{//Tintisthereturntypeofthisopertorfunction/*codeforcomputingthesumofoperandandtheTintnumberonwhichtheoperator+functionisinvokedwhichispointedtobythethispointer.Thisfunctioncomputesthesumof*thisandoperandandreturnsthesumasanewTintnumber.Itdoesnotmodify*thisoroperand(hencetheconstqualifier),ThealgorithmisAddthe_leastSignificantPartpartsandsavethecarrybit.Addthe_mostSignificantPartpartsusingthecarrybit.Store(1)and(2)inatemporaryTintnumberReturnthetemporaryTintnumberbyvalue.*/Tintresult=*this;//callstheCopyConstructorunsignedcharcarry=0;//Addtheleastsignificantpartsandcheckforanycarryresult.__leastSignificantPart +=operand.GetLeastSignificantPart();if (result._1eastSignificantPart <operand.GetLeastsignificantPart())carry=1;+=//AddthemostSignificantpartswiththecarryresult._mostSignificantPart+=carry+operand.GetMostSign!ficantPart();returnresult;)//SkeletonofaconstructorTint::Tint(longmsp,unsignedlongIsp){//Copythevaluespassedtotheconstructorintothe//correspondingdatamembers_leastSignificantPart=Isp;__mostSignificantPart=msp;)//?include"エnt?h”intmain(){TinthugeNumber(100,2000);//createaTintTintnormalNumber(1000);//andanotherTintTintsum;//sendmessageprinttohugeNumber.//ThethispointerwillbesetuptopointtohugeNumberhugenumber.Print();////ChangethesignofhugeNumberhugeNumber.FlipSign();//PrintitagainhugeNumber.Pinnt();//addhugeNumberandnormalNumberandstore//theresultinsum.Thestatementsum=hugeNumber+normalNumber//isinterpretedas//I.Invokeoperator+functiononhugeNumberandpass//normalNumberastheargument.//2.Invoketheassignmentoperator(operator=)onsum//andpasstheresultfrom(1)astheargument.//sum.operator=(hugeNumber.operators(normalNumber));sum=hugeNumber+normalNumber;//Printthereaulti.e.invokeprint()onsum.sum.Print();}///////////////////////////////////////////////////第3章C++與數(shù)據(jù)抽象///////////////////////////////////////////////////IntStack.In/*TIntStackisastackofintegers.Itprovidestheusualoprations,*PushandPop.Forthepurposeofthisdiscussion,I*musing*anIntegerStack.But,itisveryeasytoimplementageneralStack*class(aswewillseeinChapter-9)*ThisgoesinthefileIntStack.h*/*classTintstack{public://MemberFunctions//DefaultconstructorTintstack(unsignedintstacksize=DEFAULT_SIZE);Tintstack(constTIntStack&that);//CopyConstructor//AssignmentOperatorTIntStack&operator=(constTIntStack&assign);?Tintstack();//DestructorvoidPush(intthisValue);intPop();unsignedintHowMany()const;//andmanymorememberfunctionsprivate://Datamembersint*_sp;unsigned_count;unsigned_size;};///:-#include”IntStack,In”Tintstack::Tintstack(unsignedintstacksize/*=DEFAULT_SIZE*/){//Allocatememoryonlywhenstacksizeispositiveif(stackSize>0){_size=stacksize;_sp=newint[size];//Allocatememoryforstackelements//Initializeallelementstozerofor(inti=0;i!=_size;++i)_sp[i]=0;}else{_sp=0;//setthepointertotheuniquevalue_size=0;}_count=0;//noelementsonthestack)Tintstack::Tintstack(constTIntStack&source){//CodewrittenherecanaccessallregionsofclassTintStack//sincethecopyconstructorisamemberfunctionoftheclass.//TheargumentsourceisanobjectofTintstack.size=source.__size;if(_size>0){//Allocatememoryonlywhensizeispositive_sp=newint[_size];//Allocatememoryforstackelements_count=source._count;//#ofelementsonthestack//Nextcopyalltheelementsfrom"source"toourstackforinti=0;i!=_count;++i)_sp[i]=source._sp[i];)else(_sp=0;//setthepointertotheuniquevalue_count=0;//noelementsonthestack))*FunctiontoprintalltheelementsofaStack*WePop()elementssequentiallyandprinttheminthesameorder.*/voidPrintstack(TintstackthisOne){//FindoutthenumberofelementsontheStackunsignedi=thisOne.HowMany();for(unsignedj=0;j!=i;++j)cout<<"["<<thisOne.Pop()<<"]"<<endl;//Printthepopedelement)#include"IntStack?h"#include<iostream>usingnamespacestd;intmain(){//Codewrittenherecanaccessanythinginthepublicregionoftheclass//Tintstackandnothingelseinsidetheclass.TintStacka(5);//autoobject,destroyedonexitfrommain()Tintstackb(20);//autoobject,destroyedonexitfrommani()Tintstack*ip=newTintstack;//dynamicobjectfor(inti=l;i!=6;++i){//Pushconsecutiveintegersa,push(i);b.Push(-i);//negativevaluepushed)//ContinuePushoperationsonbfor(;i<=10;++i){//Pushconsecutiveintegersb.Push(-i);//negativevaluepushedPrintstack(a);//Seewhatitcontainsa=b;//AssignonestacktoanotherPinntStack(*ip);deleteip;//Whythis?seebelow;return0;)Tintstack::-Tintstack(){cout<<"ExecutingthedestructorforTエntStack'n";delete[]_sp;TintStacksoperator=(TIntStack&source);TintStacksoperator=(constTintStackssource){//Checkforassignmenttoself(oftheforma=a).1this*isthe//addressoftheobjectbeingassignedtoandsourceistheobject//beingassigned.&sourcegivestheaddressoftheobject.if(this==&source){cout<<nWarning:Assignmenttoself.\nn;return*this;)/*Ifthecountofelementsonthestackofthesourceobjectisequaltoorlessthanthesizeofthedestinationobject,nosweat.Allwehavetodoiscopythecorrespondingelementsofthestacksandthecountvariable.Ontheotherhandifthecountofthenumberofelementsonsourceobjectisbiggerthanthesizeofthedestinationobject,wehavetogetridofthememoryinsp(ofthedestinationobject)andallocateanewpieceofmemory(equaltosizeinsource)andthecopyallelements.*/if(source._count>this->_size){//Thecountofelementinsourceismorethanthesizeof//destination//Throwawaymemoryinspandallocateanewone//Seebelowforexplanation.delete[]_sp;this->_size=source._size;_sp=newint[this->_size];)//Thiscodeiscommontobothcasesdescribedabove.Walk//throughthestackandcopyelementsfor(inti=0;i!=source._count;++i)this->_sp[i]=source._sp[i];//copyelementsthis->_count=source._count;return*this;//Seebelowforexplanation)classTString{public:TString(constchar*sp){_data=newchar[strlen(sp)+l];strcpy(_data,sp);)TStringSoperator=(constTString&assign);private:char*_data;//pointertocharacterstring};TString&TString::operator=(constTStringsassign){//Wrongcode.Nocheckisdoneforassignmenttoselfdelete[]this->_data;data=newchar[strlen(assign.__data)+1];strcpy(this->_data,assign._data);return*this;}voidTintstack::Push(intwhat){if(_count<_size){//Ifthereisroomformoreelements__sp[_count]=what;//Storeelement_count++;//incrementcount}else{cout<<nStackisFull.CannotPushvalue11<<what<<endl;))intTintstack::Pop(){if(_count<=0){//Stackisemptycout<<nStackisEmpty\nn;exit(1);//Howwillweindicatefailureotherwise?//Inproductioncodewewouldthrowanexceptionhere}_count——;return_sp[_count];)unsignedTintstack::HowMany()const{return_count;

//APersonclassclassTPerson{public:TPerson(constchartheName[],constchartheAddress[]=0};constchar*GetName()const;private:char*_name;//pointertocharaterschar*_address;};classTListNode;//aforwarddeclaration-tobecompletedlaterclassTListIterator;classTList{public:TList();//CreateasimplelinkedlistunsignedHowMany()const;}classTListNode{//otherdeclarationsprivate:TListNode*_next;//pointertonextnodeTListNode*_previous;//pointertopreviousnode};classTstopWatch{public:TstopWatch();private:staticlong&_systemClock;//areferencetothesystemclock);///////////////////////////////////////////////////第4章OOP中的初始化和無用單元搜集///////////////////////////////////////////////////APersonclassclassTPerson{public:constructorchartheAddress[],longtheBirthDate);source);TPerson()constructorchartheAddress[],longtheBirthDate);source);?TPerson();voidSetNam(constchartheNewName[]);voidPrint()const;//detailsomittedforsimplicityprivate:char*_name;//pointertocharatersunsignedlong_ssn;//Socialsecuritynumber(hereintheU.S)unsignedlong_birthDate;char*_address;);TPerson::TPerson(){//assignmentstyleconstructor,notrecommended//butisstillbetterthannocodeatall.__name=0;__address=0;_ssn=0;_birthDate=0;}//APersonclassclassTPerson{public:TPerson()(unsignedlongtheBirthDate);TPerson(constcharname[],constchartheAddress[]runsignedlongtheSSN,unsignedlongtheBirthDate);TPerson&operator=(constTPerson&source);TPerson(constTPerson&source);?TPerson();voidSetNam(constcharNewName[]);voidPrint()const;//detailsomittedforsimplicityprivate:char*_name;//pointertocharatersunsignedlong_ssn;//Socialsecuritynumber(hereintheU.S)constunsignedlong_birthDate;char*_address;//asanarrayofcharacters};TPerson::TPerson(unsigned long theBirthDate)_birthDate(theBirthDate)//initializarionphasebeginshere{//Assignmentphaseoftheconstructorbeginshere_name=0;_ssn=0;_address=0;classTCar{private:unsigned_weight;//weightofcar,inpoundsshort_driveType;//fourwheelortwowheelTPerson__owner;//whoownsthiscar//otherdetailsnotimportantpublic:Tear(constcharname[],constcharaddress[],unsignedlongssn,unsignedlongownerBirthDate,unsignedweight=900,shortdriveType=2);)Tear::Tear(constcharname[],constcharaddress[],unsignedlongssn,unsingedlongownerBirthDate,unsignedweight):_owner(name,address,ssn,ownerBirthDate)//InitializestheTPersonobject,_owner,bycallinganappropriate//constructor,supplyingtheowner1sname,address,ssn,andbirthdate|//codeforconstructornotshownforbrevityofexample)classTDate{public:enumEMonth{eJan=1,eFeb,eMar,eApr,eMay,eJun,eJul,eAug,eSep,eOct,eNov,eDec};//SimpleconstructorsTDate(unsignedday,EMonthmon,unsignedyear);TDate(constchardate[]);//datepassedinasastringTDate();//setsdatefromtheoperatingsystemdateunsignedGetYear()const;EMonthGetMonth()const;unsignedGetDay()const;//dayofthemonth//conveniencefunctions.voidAddToYear(intincrement);//IncermentcanbenegativevoidAddToMonth(intincrement);//IncrementcanbenegativevoidAddToDay(intincrement);//Incrementcanbenegative//Comparisonoperatorsbooloperator==(constTDate&second)const;booloperator!=(constTDate&second)const;TStringGetDate()const;//Returnsastringrepresentationprivate:short_year;//someimplementationdatashort_day;EMonth_month;};//APersonclassclassTPerson{public:TPerson()(constcharbirthDate[]);TPerson(constcharname[]tconstchartheAddressロ,unsignedlongtheSSN,constcharbirthDate[]);TPerson&operator=(constTPerson&source);TPerson(constTPerson&source);?TPerson();voidSetNam(constchartheNewName[]);voidPrint()const;//detailsomittedforsimplicityprivate:char*_name;//pointertocharatersunsignedlong_ssn;//Socialsecuritynumber(hereintheU.S)constTDate_birthDate;char*_address;//asanarrayofcharacters};intmain(){//allocateadynamicarrayof1000characterschar*p=newchar[1000];char*q=newchar[1000];anotherpieceofdynamicmemory//Codethatusespandqforsomeoperationsp=q;//Assignqtopoverwritingtheaddressinp/*whathappenedtothe1000charactersofstoragethatppointedto?pandqpointtothesameplaceandnoonepointstotheoldPstorage!itisstillthere,takingupspace,butitcannotbeaccessed(used)bytheprogramanymore.Thisiscalledgarbage.*/)intmain(){char*p;char*q;p=newchar[1024];//allocateadynamicarrayofIkcharactersII...Useitq=p;//Pointeraliasingdelete[]p;P=0;//NowqisadanglingreferenceIIlfweattempt*q=1A1,itwouldbedisastrous//FirstConstructorTPerson::TPerson(constcharbirthDate[]):_ssn(〇),__name(0),_birthDate(birthDate),__address(0){/*emptyconstructorbody*/)char*Strdup(constchar*src){//Helperfunctionchar*ptr=newchar[strlen(src)+l];strcpy(ptr,src);returnptr;)//SecondConstructorTPerson::TPerson(constchartheName[],constchartheAddress[],unsignedlongtheSSN,constchartheBirthDate[]):__ssn(theSSN,_birthDate(theBirthDate){//Initialize_name,__address,etc._name=(theName?Strdup(theName):0);_address=(theAddress?Strdup(theAddress):0);}//DestructorTPerson::?TPerson(){delete[]_name;delete[]_address;)voidTPerson::SetName(constcharnewName[]){unsignedoldLength=_name?strlen(_name):0;unsignednewLength=newName?strlen(newName):0;if(oldLength<newLength){//Notenoughspacein_namedelete[]_name;//GarbageCollection//Usestrdupfunctiondefinedearlier_name=(newName?Strdup(newName):0;}})classTPoint2D{public:TPoint2D(doublex=0.0,doubley=0.0);DistanceTo(constTPoint2D&otherPoint);//Copyconstructorandassignmentoperatoromittedwillbe//providedbythecompilerotherdetailsomittedprivate:double_xcoordinate;double_ycoordinate;TPerson::TPerson(constTPerson&source)://Initializeappropriatedatamembersssn(source.ssn),_birthDate(source.birthDate){//Copy_nameand_addressifnotNULL//Weneedtocheckifsourcecontainsnon-zeropointers//andthenallocatememoryandcopythedata.//WehavealreadywrittenStrdup()forthispurpose//So,goaheadanduseit.this->_name=source._name?Strdup(source._name):0;//Nextcopy_addressinasimilarfashionthis->_address=source._address?Strdup(source._address):0;TPoint2D::operator=(constTPoint2D&source){this->xcoordinate=source.__xcoordinate;//copythexfieldthis->ycoordinate=source._ycoordinate;//copytheyfieldreturn*this;}TPerson&TPerson::operator=(constTPerson&source){if(this==&source)//AssignmenttoSelf,Donothingreturn*this;//Copy(assign)alltheprimitivedatathis->_ssn=source._ssn;//Nextweneedtocopythecharacterinname//Itispossibethatthereisenoughroominname.//Ifsojustcopythecharacters.Otherwisediscardthe//existingmemorypointedbyname,thenallocateanew//pieceofmemoryandfinallycopythecharacterif(source._name!=0){//Anythingtocopy?intnameLength=strlen(source._name);intthisNameLength=(this->_name)?strlen(this->_name):0;if(nameLength<=thisNameLength)//theeasycasestrcpy(this->_name,source._name);else{//Thenot-so-easycasedelete[]this->_name;name=newchar[nameLength+1];//+1forthetermination0strcpy(this->__name,source._name);}}else{delete[]this->_name;thisー〉name=0;//repeatthestepsforaddressalsoif(source._address!=0){intaddressLength=strlen(source._address);intthisAddrLength=(this->_address)?strlen(this->_address):0;if(addressLength<=thisAddrLength){//theeasycasestrcpy(this->_addressrsource._address);}else{//Thenot-so-easycasedelete[]this->_address;__address=newchar[addressLength+1];//+1fortheterminating0strcpy(this->_addresszsource._address);)else(delete[]this->_address;this->_address=0;)return*this;)//APersonclassclassTPerson{public:TPerson()(constcharbirthDate[]);TPerson(constcharname[],constchartheAddress[],unsignedlongtheSSN,constcharbirthDate[]);TPerson&operator=(constTPerson&source);TPerson(constTPerson&source);?TPerson();booloperator=(constTPerson&other)const;booloperator!=(constTPerson&other)const;voidSetName(constchartheNewName[]);voidPrint()const;//detailsomittedforsimplicityprivate:char*_name;//pointertocharatersunsignedlong_ssn;//Socialsecuritynumber(hereintheU.S)constTDate_birthDate;char*_address;//asanarrayofcharactersboolTPerson::operator==(constTPerson&other)const{if(this==&other){returntrue;}//Comparingaliasesif(this->ssn==other._ssn&&thisー〉birthDate==othe,_birthDate){//Nowcomparenamesif(strcmp(this->_name,other._name)==0)//strcmpisalibraryfunctionreturntrue;Ireturnfalse;//theyarenotequal}boolTPerson::operator!=(constTPerson&other)const{return!(*this==other);//wecanalsowrite;//return!(this->operator==(other);)classTSemaphore{public://DefaultconstructorTSemaphore();//CalledbyclientstoacquiretheSemaphoreboolAcquire();//Callthiswhenyounolongerneedexclusiveaccesstothe//resourcevoidRelease();//Howmanytasksarealreadywaitingonthisresource?unsignedGetWaiters()const;private://TSemaphoreobjectscannotbecopiedorassignedTSemaphore(constTSemaphore&other);TSemaphore&operator=(constTSemaphore&other);//Detailsomitted);classX{public://memberfunctionvoidf();private:TSemaphore_sem;);voidX::f(){//MemberfunctionofX//Beforeanythingracquirethelockingsemaphore_sem,Acquire();//dowhateveryouhavetodoif(/*somecondition*/){/*domorestuff*/_sem.Release();return;}else{/*dosomeotherstuff*/_sem.Release();I)classTAutoSemaphore{public:TAutoSemphore(TSemaphore&sem):_semaphore(sem){.semaphore.Acquire();)~TAutoSemaphore(){_semaphore.Release();)private:TSemaphore&_semaphore;};voidX::f(){//MemberfunctionofX//Beforeanything,createaTAutoSemaphoreobject//ThisalsoacquiresthesemaphoreTAutoSemphoreautosem(_sem);//dowhateveryouhavetodoif(/*somecondition*){/*domorestuff*/return;}else{/*dosomeotherstuff*/}//destructorofautosemautomaticallyreleasesthesemaphore_sem//onexitfromf())classTTracer{public:#ifdefDEBUGTTracer(constcharmessage[]):_msg(message){cout<<n>>Entern<<_msg<<endl;}TTracer(){cout<<n<<Exitn<<_msg<<endl;}private:constchar*_msg;#elseTTracer(constcharmessage[]){}-TTracer(){)#endif};classTLicenseToken;//forwarddeclarationclassTLicenseServer{public://Constructor-createsanewlicenseserverwithmaxUserslicensesTLicenseServer(unsignedmaxUsers);^TLicenseToken*CreateNewLicense();private://ObjectscannotbecopiedorassignedTLicenseServersoperator=(constTLicenseServersother);unsigned_numlssued;unsigned__maxTokens;//manydetailsomitted};classTLicenseToken{public:TLicenseToken();?TLicenseToken();private:TLicenseToken(constTLicenseTokenSother);TLicenseTokensoperator=(constTLicenseTokenSother)//manydetailsomitted};//classTStringI*★Astringclassimplementation.ItisbasedontheASCIIcharacterset.*TStringobjectscanbecopiedandassigned.Classimplementsdeepcopy*Usethisclassinsteadof""stringsofcharacters.夫/?include<iostream>?include<cstring>?include<cstdlib>?include<cctype>usingnamespacestd;classTString{public://Constructors//CreateanemptystringobjectTString();//Createanewstringobjectwhichconstainsthecharacterspointed

//bys.smustbeNULLterminated.Charactersarecopiedfroms.TString(constchar*s);//CreateastringcontainingthesinglecharacteraCharTString(charaChar);TString(constTString&arg);//copyconstructor?TString();//Destructor//AssignmentoperatorsTStringsoperator=(constTString&arg);TStringsoperator=(constchar*s);TStringsoperator=(chars);//Returnsthenumberofcharacterscurrentlystoredintheobject//intsize()const;//Returnsasubstringwhichrepresentsthestringstarting//atposnoflengthlenTStringoperator()(unsignedposn,unsignedlen)const;//Returnsthecharacteratncharoperator()(unsignedn)const;//Returnsareferencetothecharacteratnconstchar&operator[](unsignedn)const;//Returnsapointertotheinternaldata.Carefulconstchar*c_str()const{return_str;}//Thesemethodsmodifytheoriginalobject//Appendsthecharacterinotherto*thisTString&operator+=(constTString&other);//ChangecaseofallcharactersinthisstringTString&ToLower();//changeuppwrcasecharacterstolowercaseTStringsToUpper();//changelowercasecharacterstouppercaseprivate://lengthisthenumberofcharactersstoredintheobject.//Butthememorypointedbystrisatleastlength+1long.unsigned__length;char*_str;//pointertocharacters);//Non-memberfunctionsthatsupportTStringclass//ReturnsanewTStringobjectwhichisaconcatenationofoneandtwoTStringoperators(constTString&one,constTString&two);basedonASCIIcharacterset.containthesamecharacters.//Input/Outputoperators.Seechapter-7foradetaileddiscussionostream&operator<<(ostream&o,constTString&s);istream&operator>>(istreamSstream,TStbasedonASCIIcharacterset.containthesamecharacters.//Relationaloperators,comparisonis//Twostingobjectsareequaliftheybooloperator==(constTString&first,constTString&second);booloperator!=(constTStringsfirst,constTStringssecond);booloperator<(constTStringsfirst,constTStringssecond);booloperator>(constTStringsfirst,constTStringssecond);booloperator>=(constTString&first,constTString&second);booloperator<=(constTString&first,constTString&second);TString::TString(){_str=0;_length=0;)TString::TString(constchar*arg){if(arg&&*arg){//pointerisnot0and//alsopointstovalidcharacters_length=strlen(arg);_str=newchar[_length+l];strcpy(_str,arg);}else{_str=0;_length=0;TString::TString(charaChar){if(aChar){_str=newchar[2];_str[0]=aChar;_str[1]=1\01;_]_ength=1;}else{__str=0;__length=0;}}TString::?TString(){if(_str!=0)delete[]_str;}//Copyconstructor.Performsadeepcopy.Allocatesmemoryfor//charactersandthencopiesthecharacterstothis.TString::TString(constTString&arg){if(arg._str!=0){this->_str=newchar[strlen(arg.__str)+1];strcpy(this->_str,arg._str);一Length=arg._length;}else{_str=0;_length=0;TString&TString::operator=(constTString&arg){if(this==&arg)return*this;if(this->_length>=arg._length){//*thisisbigenoughif(arg._str!=0)strcpy(this->__strzarg._str);elsethis->_str=0;}this->_length=arg._length;return*this;)TString&TString::operator=(constchar*s){if(s==0II*s==0){//sourcearrayisempty,Make"this"emptytoodelete[]_str;_length=0;__str=0;return*this;}intslength=strlen(s);if(this->_length>=slength){//*thisisbigenoughstrcpy(this->_strzs);this->_length=slength;return*this;}//Hmm,*thisdoesn1thaveenoughapace;_argisbiggerdelete[]_str;//Safethis->_length=arg.Size();if(_length){_str=newchar[_length+l];strcpy(_str,arg._str);}else_str=0;return*this;//Alwaysdothis)TString&TString::operator=(charcharToAssign){chars[2];s[0]=charToAssign;s[l]=,ヽ(T;//Usetheotherassignmentoperatorreturn*this=s;)intTString::Size()const{return_length;}TString&TString::operator+=(constTString&arg){if(arg.Size()){//Memberfunctionscan

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論