




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
C++ProgramDesignAnIntroductiontoProgrammingandObject-OrientedDesignARichHistoryMS-DOSBASICWindowsVisualBASICIE,IISVisualStudio1995Internet1990GUI1981PC2002XML
WebServicesRapidlyChangingTechnologyComputationalpowerCPUpowerdoublingevery18monthsGraphics5xperyearStorage2xperyearNetworking4xperyearNewdevicesMobilescreens,cameras,TabletPC,PocketPCs,mobilephonesConnectivityWirelessHigh-speedInternetChap.2C++:Thefundamentalsfunctionmain()includecommentsdefinitionssimpleinteractiveinputandoutputinteger,floating-point,andcharactertypesinteger,floating-point,andcharacterliteralsKeyConceptsC++namesdeclarationsexpressionsusualunaryconversionsusualbinaryconversionsoperatorprecedenceoperatorassociativityiostreaminsertionandextractionAFIRSTPROGRAM//Program2.1:Displaygreetings//Author:BryanZeng//Date:7/24/2002#include<iostream>usingnamespacestd;intmain(){ cout<<"Helloworld!"<<endl;return0;}Processedbythepreprocessoroperandinsertionoperator程序運(yùn)行的結(jié)果nameoftheprogramoutputoftheprogramASECONDPROGRAM#include<iostream>usingnamespacestd;intmain(){ //Inputprice cout<<"Purchaseprice?";
floatPrice; cin>>Price; //Computeandoutputsalestax cout<<"Salestaxon$"<<Price<<"is"; cout<<"$"<<Price*0.04<<endl;
return0;}extractionoperatorinsertionoperatorScreencaptureASSIGNINGAVALUExyWhatarewegoingtodo?x-coordinatey-coordinateASSIGNINGAVALUE#include<iostream>usingnamespacestd;intmain(){ //Inputlinesparameters cout<<"Slopeofline(integer)?";
intm;//Lineslope cin>>m; cout<<"Interceptofy-axis(integer)?";
intb;//y-intercept cin>>b;ASSIGNINGAVALUE //Inputx-coordinateofinterest cout<<"x-coordinateofinterest(integer)?";
intx;//x-coordinateofinterest cin>>x; //computeanddisplayy-coordinate
inty; y=m*x+b; cout<<"y="<<y<<"whenm="<<m<<";"; cout<<"b="<<b<<";x="<<x<<endl;
return0;}ScreencaptureFUNDAMENTALC++OBJECTStheintegerobjectsthefloating-pointobjectsthecharacterobjectsIntegerobjecttypesshort(16bits)int(32bits)long(32bits)thesizeofintisimplementationdependentCharacterobjecttypesCharactersareencodedusingsomeschemewhereanintegerrepresentsaparticularcharacter.Foeexample,theinteger98mightrepresentthelettera.‘a(chǎn)’<‘b’<‘c’<…<‘z’‘0’<‘1’<‘2’<…<‘9’Theoperatorsdefinedontheintegertypesaredefinedonthecharactertypesaswell.‘A’+1gives‘B’‘J’+3resultsin‘M’Floating-pointobjecttypesfloat(32bits)double(64bits)longdouble(80bits)CONSTANTSStringandcharacterconstantsIntegerconstantsFloating-pointconstantsStringandcharacterconstants“HelloWorld!”“HelloWorld!\n”(“HelloWorld!\012”)“\“HelloWorld!\””MemoryallocationforastringliteralHelloWorld!0010040010041010042……010052Integerconstants23451015523L45L101L55L023077L045010base8numbers0380930779notvalidconstants0x2a0x450xffL0xA1ebase16numbersExampleofconstants#include<iostream>usingnamespacestd;intmain(){ cout<<"Displayintegerconstants\n"<<endl; cout<<"Octal023is"<<023<<"decimal"<<endl; cout<<"Decimalconst23is"<<23<<"decimal"<<endl; cout<<"Hexconst0x23is"<<0x23<<"decimal"<<endl;
return0;}ScreencaptureFloating-pointconstants2.343.1415.21L45.e+232.3E-4Example#include<iostream>usingnamespacestd;intmain(){ cout<<230.e+3<<endl; cout<<230E3<<endl; cout<<230000.0<<endl; cout<<2.3E5<<endl; cout<<0.23e6<<endl; cout<<.23E+6<<endl;
return0;}NAMESKeywords(reservedwords)Identifiers:anamedefinedbyandgivenmeaningtobytheprogrammer.SomeofthekeywordsasmelsefloatoperatorautoenumforprivateboolexplicitfriendthrowbreakexterngototruecasefalseinlinetypedefExamplesofidentifiersWordCountTimeNumberOfStudentsDEFINITIONSintx;intWordCnt,Radius,Height;floatFlightTime,Mileage,Speed;Examplesofdefinitions#include<iostream>usingnamespacestd;intmain(){
floatf;
inti;
charc;
doubled; cout<<"f'svalueis"<<f<<endl; cout<<"i'svalueis"<<i<<endl; cout<<"c'svalueis"<<c<<endl; cout<<"d'svalueis"<<d<<endl;
return0;}Initialvaluesalwaysgiveobjectsaninitialvalue!CASESTUDYCOMPUTINGAVERAGEVELOCITYinput:startandendmilepost,elapsedtime(h/m/s)output:averagevelocity(milesperhour).CASESTUDYStep1.Issuethepromptsandreadtheinput.Step2.Computetheelapsedtimeinhours.Step3.Computethedistancetraveled.Step4.Computetheaveragedvelocity.Thestepstosolvingtheproblem:#include<iostream>usingnamespacestd;intmain(){ cout<<"Allinputsareintegers!\n"; cout<<"Startmilepost?";
intStartMilePost; cin>>StartMilePost; cout<<"Endtime(hoursminutesseconds)?"; intEndHour,EndMinute,EndSecond; cin>>EndHour>>EndMinute>>EndSecond; cout<<"Endmilepost?";
intEndMilePost; cin>>EndMilePost;
floatElapsedTime=EndHour+(EndMinute/60.0)+(EndSecond/3600.0);
intDistance=EndMilePost-StartMilePost;
floatVelocity=Distance/ElapsedTime;
cout<<"\nCartraveled"<<Distance<<"milesin"; cout<<EndHour<<"hrs"<<EndMinute<<"min"<<EndSecond<<"sec\n"; cout<<"Averagevelocitywas"<<Velocity<<"mph"<<endl;
return0;}expressionsassignmentCHAPTER3ModifyingobjectsassignmentoperationassignmentconversionsassignmentprecedenceandassociativitystringsEzWindowsextractionoperationsconstdeclarationscompoundassignmentoperationsinputwithcinincrementanddecrementoperationAssignmentintScore1=90;intScore2=75;inttemp=Score2;Score2=Score1;Score1=temp;9075907575909075759075Score1Score2temptosvaluesofScore1andScore2Assignmentconversionsintx=0;x=3.9;shorts1=0;longi2=65535;s1=i2;shortm1=0;longn2=65536;m1=n2;cout<<x<<s1<<m1?3-10Assignmentprecedenceandassociativityx=y=z+2;x=(y=(z+2));compoundassignmenti=i+5;i+=5;i=i+1;i+=1;++i;i=i-1;i-=1;--i;IncrementandDecrementinti=4;intj=5;intk=j*++i;cout<<k<<i;inti=4;intj=5;intk=j*i++;cout<<k<<i;255205TheStringClassstringMessage1=“Enteryourpassword:”;stringMessage2=Message1;stringFirstName=“Zach”;stringLastName=“Davidson”;stringFullName=FirstName+“”+LastName;FirstName+=LastName;stringDate=“March7,1994”;intlength=Date.size();casestudyconvertingdatesfromAmericanformattointernationalformatDecember29,195329December1953MonthDayYearDayMonthYearsolution//Promptforandreadthedatecout<<“EnterthedateinAmericanformat”<<“(e.g.,December29,1953):”;charbuffer[100];cin.getline(buffer,100);stringDate=buffer;solutiontoextractthemonth:inti=Date.find(“”);stringMonth=Date.substr(0,i);December29,1953solutiontolocateandextracttheday:intk=Date.find(“,”);stringDay=Date.substr(i+1,k-i-1);December29,1953solutionDecember29,1953toextracttheyear:stringYear=Date.substr(k+2,Date.size());solutiontodisplaythedateinthenewformat:stringNewDate=Day+“”+Month+“”+Year;cout<<“Originaldate:”<<Date<<endl;cout<<“Converteddate:”<<NewDate<<endl;screencaptureezwinobjectsY-coordinate:DistancefromtopofscreenX-coordinate:DistancefromleftedgeofscreenHeightofwindowWidthofwindowWindowsApiDemo//Program3.6:ApiDemo#include<iostream>#include<string>#include<rect.h>usingnamespacestd;intApiMain(){constintWidth=8;constintHeight=7;intLawnLength=6;intLawnWidth=5;intHouseLength=3;intHouseWidth=2;ClicktoviewsourceSimpleWindowWindow(“ApiDemo”,Width,Height);Window.Open();RectangleShapeLawn(Window,Width/2.0,Height/2.0, Green,LawnLength,LawnWidth);Lawn.Draw();RectangleShapeHouse(Window,Width/2.0,Height/2.0, Yellow,HouseLength,HouseWidth);House.Draw();cout<<"Typeacharacterfollowedbya\n"<<"returntoremovethewindowandexit"<<endl;charAnyChar;cin>>AnyChar;Window.Close();return0;}CHAPTER4Controlconstructs
booltypeRelationaloperatorsshort-circuitevaluation
if-elsestatement
switchstatement
breakstatement
enumstatement
forconstruct
whileconstruct
doconstructinfiniteloopsinvariantsKeyConceptsABOOLEANTYPEboolP=true;boolQ=false;boolR=true;boolS=false;Booleanoperators:P;//PhasvaluetrueP&&R;//logicalandistruewhenbothoperands aretrueP||Q;//logicaloristruewhenatleastoneof theoperandsistrueP&&S;//logicalandisfalsewhenatleastoneoftheoperandsisfalse!R;//logicalnotisfalsewhentheoperandis trueThelogicaloperatorsarealsodefinedfortheintegraltypeobjectssuchasintandchar.inti=1;intj=0;intk=-1;intm=0;i//iisnonzeroi&&k//bothoperandsarenonzero!j//notistruewhenoperandiszeroThefollowingexpressionsaretrue.Thefollowingexpressionsevaluatetofalse.j||m//bothoperandsarezero!k//notisfalsewhentheoperandisnonzeroRelationaloperatorsinti=1;intj=2;intk=2;charc=‘2’;chard=‘3’;chare=‘2’;Thefollowingexpressionsaretrue.c==ei!=ki<jd>ej>=kThefollowingexpressionsarefalse.i==jc!=ej<kd<=ci>=kOperatorprecedencei+l<j*4&&!P||QOperationUnaryoperatorsMultiplicativearithmeticAdditivearithmeticRelationalorderingRelationalequalityLogicalandLogicalorAssignmentPrecedenceofselectedoperatorsarrangedfromhighesttolowest(((i+1)<(j*4))&&(!P))||QShort-circuitevaluation(i!=0)&&((j/i)>5)Conditionalexecutionusingtheif-elsestatementExpressionAction1Action2truefalseif(Expression)Action1
else
Action2examplecout<<"Pleaseentertwonumbers:";intValue1,Value2;cin>>Value1>>Value2;intLarger;if(Value1<Value2)Larger=Value2;elseLarger=Value1;cout<<"Thelargerof"<<Value1<<"and"<<Value2<<"is"<<Larger<<endl;conditionalexecutionusingtheswitchstatementswitch(command){ case'u': cout<<"Moveup"<<endl; break; case'd': cout<<"Movedown"<<endl; break; case'l': cout<<"Moveleft"<<endl; break; case'r': cout<<"Moveright"<<endl; break; default: cout<<"Invalidcommand"<<endl;}computingarequestedexpressionviewsourcefile32+104casestudyIterationusingthewhilestatementExpressionActiontruefalsecasestudycomputeaverageofalistofvaluesClicktoviewsourceCasestudy:validatingadateWenextdevelopaprogramthatpromptsauserforadateandthendetermineswhetherthatdateisvalid.Pleaseenteradate(mmddyyyy):1312002Invalidmonth:13Example:HowtodetermineleapyearsYearsdivisibleby4Yearsdivisibleby100Yearsdivisibleby400ShadedareasrepresentleapyearsClicktoviewsourceSimplestringandcharacterprocessingModelfortextprocessing//prepareforstringprocessing//extractandprocessstringswhile(cin>>s){//preparetoprocessstrings//processcurrentstrings//preparetoprocessnextstring}//finishstringprocessing…………………………Clicktoviewsourcecasestudy:Amorecomplicatedtextprocessor:clicktoviewsourceEchoinputtostandardoutput,convertinguppercasetolowercase.screencaptureIterationusingtheforconstructfor(ForInit;ForExpression;PostExpression)ActionInitializationsteptopreparefortheforloopevaluationPreparationfornextiterationoftheforloopLogicalexpressionthatdetermineswhethertheactionistobeexecutedActiontobeperformedforeachiterationoftheforloopexampleComputen!:cout<<"Pleaseenterapositiveinteger:";intn;cin>>n;intnfactorial=1;for(inti=2;i<=n;++i){nfactorial*=i;}cout<<n<<"!="<<nfactorial<<endl;CHAPTER5Functionbasicsfunctionsvalueparametersinvocationandflowofcontrolheaderfilesfunctionprototypingactivationrecordsdefinedirectivesconditionalcompilationiostreamfunctionalitypseudorandomnumbersiomanipmanipulatorsformattedoutputfstreamclassifstreamfstreamclassofstreamstdliblibraryexit()functionassertlibrarytranslationunitcastingKeyConceptsfunctionbasicsconsiderthefollowingquadraticexpression:therootsoftheexpressionaregivenby:clicktoviewsourcefunctionbasicsdoubleradical=sqrt(b*b-4*a*c);functionsqrt()parameters(arguments)returnsavalueoftypedoubleinterfacespecificationdoublesqrt(doublenumber);#include<cmath>mathlibraryfunctioninterfacefunctiontypeorreturntypefunctionnameheaderfileparameter(formalparameter)interfacespecificationFunctionTypeFunctionName(ParameterList)TypeofvaluethatthefunctionreturnsIdentifiernameoffunctionAdescriptionoftheformtheparameters(ifany)aretotakeParameterDeclaration,…,ParameterDeclarationDescriptionofindividualparametersParameterTypeParameterNameFunctionprototypingintPromptAndExtract();floatCircleArea(floatradius);boolIsVowel(charCurrentCharacter);formalparameterexamplescout<<sqrt(14)–sqrt(12);doubleQuarticRoot=sqrt(sqrt(5));doublex=sqrt();doubley=sqrt(5,3);invalidinvocationsoffunctionactualparameterthefstreamlibraryopenareaddataopenawritedataclicktoviewanexamplerandomnumbers//program5.6:displaypseudorandomnumbers#include<iostream>#include<stdlib>#include<time.h>usingnamespacestd;intmain(){srand((unsignedint)time(0));
for(inti=1;i<=5;++i)cout<<rand()%100<<endl;
return0;}CHAPTER6programmer-definedfunctionsinvocationandflowofcontrolparametersprototypesactivationrecordsreturnstatementlocalobjectscopeglobalobjectsnamereuseimplementationfileheaderfilestandardclassostringstreamstandardclassistringstreamclassLabelStandardTemplateLibraryreferenceparametersconstantparametersdefaultparametersfunctionoverloadingfunctionoverloadresolutionrecursionKeyConceptsProgrammer-definedfunctionsFunctiondefinitionsyntaxAfunctiondefinitionincludesbothadescriptionoftheinterfaceandthestatementlistthatcomprisesitsactions.Clicktoviewanexample.thelocalscopeC++’sscoperulesstatethatalocalobjectcanbeusedonlyintheblockandinthenestedblocksoftheblockinwhichithasbeendefined.ClicktoviewexamplesReferenceparametersClicktoviewexample1Clicktoviewexample2PassingobjectsbyreferenceClicktoviewexampleConstantparametersClicktoviewexampleDefaultparametersClicktoviewexampleFunctionoverloadingClicktoviewexampleRecursivefunctionsconsiderthefollowingexample:ifn=0ifn
≥1ifn=0ifn
>0clicktoviewsourceCHAPTER7Theclassconstructandobject-orienteddesignclassconstructinformationhidingencapsulationdatamembersmemberfunctionsconstructorsinspectorsmutatorsfacilitatorsconstfunctionsaccessspecification:publicandprivateobject-orientedanalysisanddesignKeyConceptsprogrammer-definedtypesclassClassName{
public: //Prototypesforconstructors //andpublicmemberfunctions //anddeclarationsforpublic //dataattributesgohere. ……
private: //Prototypesforprivatedata //membersanddeclarationsfor //privatedataattributesgohere. ……};user-definedclassinactionclassRectangleShape{
public: RectangleShape(SimpleWindow&Window,
floatXCoord,floatYCoord, color&color,floatWidth,floatHeight);
voidDraw(); colorGetColor()const;
floatGetWidth()const;
voidSetColor(constcolor&Color);
private:
floatWidth; colorColor;};datamembers(attributes)inspectorsmutatorfacilitatormemberfunctionsconstructoraccessspecifieruser-definedclassinaction//program7.1:user-definedclass#include<rect.h>SimpleWindowW("MAINWINDOW",8.0,8.0);intApiMain(){W.Open();RectangleShapeR(W,4.0,4.0,Blue,2.0,3.0);R.Draw();return0;}ClicktoviewSourceInstantiationusingtheRectangleShapeclassClicktoviewsourceCHAPTER8ImplementingabstractdatatypesdataabstractionabstractdatatyperuleofminimalityprincipledefaultconstructorscopyconstructorsmemberassignmentinspectorsoverloadinginsertionandextractionoperatorsmutatorsfacilitatorsconstmemberfunctionsdestructorsauxiliaryfunctionsandoperatorsoperatoroverloadingreferencereturnpseudorandomnumbersequenceKeyConceptsRationalADTbasicsArationalnumberistheratiooftwointegersandistypicallyrepresentedinthemannera/b.Thebasicarithmeticoperationshavethefollowingdefinitions:RationalADTbasicsAfterdevelopmentofADTRational,weareabletodo:Rationala(1,2);//a=1/2Rationalb(2,3);//b=2/3cout<<a<<“+”<<b<<“=”<<(a+b)<<endl;RationalADTbasicsWhatweneedtodo:Constructtherationalnumberwithdefaultorparticularattributes.Add,subtract,multiply,anddividetherationalnumbertoanotherrationalnumber.Copythevalueoftherationalnumbertoanotherrationalnumber.Comparetherationalnumbertoanotherrationalnumber.Displaythevalueoftherationalnumber.Extractthevalueoftherationalnumber.//program8.1:DemonstrateRationalADT#include
<iostream>#include
"rational.h"usingnamespacestd;intmain(){Rationalr;Rationals;cout<<"Enterrationalnumber(a/b):";cin>>r;cout<<"Enterrationalnumber(a/b):";cin>>s;Rationalt(r);RationalSum=r+s;RationalProduct=r*s;cout<<r<<"+"<<s<<"="<<Sum<<endl;cout<<r<<"*"<<s<<"="<<Product<<endl;return0;}copyconstructorextractionoperationinsertionoperationarithmeticoperationRationalinterfacedescriptionClicktoviewsourceImplementingtherationalclassClicktoviewsourceCHAPTER9Listsone-dimensionalarraysarraysubscriptingarraysasparametersarrayelementsasparameterscharacterstringsStandardTemplateLibrary(STL)containerclassvectorvectorsubscriptingvectorresizingstringsubscriptingiteratorsiteratordereferencingvectorofvectorstablematricesmemberinitializationlistmultidimensionalarraysKeyConceptsone-dimensionalarraysBaseTypeID[SizeExp];TypeofValuesinlistNameoflistBracketedconstantexpressionindicatingnumberofelementsinlistone-dimensionalarrayexamplesconstintN=20;constintM=40;constintMaxStringSize=80;constintMaxListSize=1000;intA[10];charB[MaxStringSize];floatC[M*N];intValues[MaxListSize];seeexamples----------A[0]A[1]A[2]A[3]A[4]A[5]A[6]A[7]A[8]A[9]A(uninitialized)one-dimensionalarrayexamplesone-dimensionalarrayexamplesinti=7;intj=2;intk=4;A[0]=1;A[i]=5;A[j]=A[i]+3;A[j+1]=A[i]+A[0];A[A[j]]=12;1-863--512-A[0]A[1]A[2]A[3]A[4]A[5]A[6]A[7]A[8]A[9]ArrayinitializationintFrequency[5]={0,0,0,0,0};intTotal[5]={0};intSub[5]({0,0,0,0,0});intCount[5]({0});intDigits[]={0,1,3,4,5,6,7,8,9};intZero[]={0};charAlphabet[]={‘a(chǎn)’,‘b’,‘c’,‘d’,‘e’};RationalR[10];NoteArraysdefinedintheglobalscopewithfundamentalbasetypeshavetheirarrayelementssetto0unlessthereisexplicitinitialization.Arraysdefinedinalocalscopewithfundamentalbasetypeshaveuninitializedarrayelementsunlessthereisexplicitinitialization.CharacterstringarrayscharLetters[]=“abcdefghijklmnopqrstuvwxyz”;charG[]=“Hello”;‘H’‘e’‘l’‘l’‘o’‘\0’G[0]G[1]G[2]G[3]G[4]G[5]G“nullcharacter”casestudyDisplayinputsinreverseorder.(Clickheretoviewsource)restrictionsontheuseofarraysafunctionreturntypecannotbeanarray;anarrayconnotbepassedbyvalue;anarraycannotbethetargetofanassignment;thesizeofthearraymustbeacompile-timeconstant;anarraycannotberesized.containerclassesStandardTemplateLibrary(STL)dequelistpriority_queuequeuestackvectormapsetcontaineradaptersclassvectorThevectorclasstemplateprovidesfourconstructorsfordefiningalistofelements:adefaultconstructortodefineanemptylist.acopyconstructortomakeacopyofanexistinglist.aconstructorwithaparameterthatspecifiestheinitialsizeofthelist,theelementsareinitializedusingthedefaultconstructorofthelistelementtype.aconstructorwithtwoparameters,thefirstparameterspecifiestheinitialsizeofthelist,thesecondparameterspecifiestheinitialvalueofeachlistelement.casestudyconstintN=20;constintM=40;cout<<“Sizeoflisttoproduce:”;intlength;cin>>length;Rationalr(1,2);vector<int>A(10);vector<char>B(M);vector<float>C(M*N);vector<int>D(length);vector<Rational>E(N);vector<Rational>F(N,r);vector<int>G(10,1);vector<char>H(M,‘h’);vector<float>I(M*N,0);vector<int>J(length,2);vectorcopyandassignmentvector<Rational>R(E);vector<int>S(G);vector<int>T(J);vector<int>U(10,4);vector<int>V(5,1);44444444444444444444111114444444444UVUVV=U;Theassignmentoperator=isamemberoperatorofthevectorclassRandomlyaccessingavector’selementsTheprincipalrandomaccessmethodsareoverloadingofthesubscriptoperator[].A[0]=57;cout<<A[5];Sequentialaccessmethodsrestrictions:bidirectionalunidirectionalThevectorsequentialaccessmethodsareimplementedusingiterators.14723512621114sentinelvector<int>A(5);……vector<int>::iteratorq++q;--q;14723512621114AA.begin()A.end()A.rend()A.rbegin()vector<int>List(5);for(inti=0;i<List.size();++i){List[i]=100+i;}100101102103104typedefvector<int>::iteratoriterator;typedefvector<int>::reverse_iteratorreverse_iterator;Listiteratorp=List.begin();cout<<*p<<“”;++p;cout<<*p<<“”;++p;cout<<*p<<“”;--p;cout<<*p<<“”;100101102101100101102103104Listiteratorq=List.rbegin();cout<<*q<<“”;++q;cout<<*q<<“”;++q;cout<<*q<<“”;--q;cout<<*q<<“”;104103102103intSum=0;for(iteratorli=List.begin();li!=List.end();++li){Sum=Sum+*li;}atypicaluseofiterators:PassingavectorVectorobjectscanbeusedlikeobjectsofothertypes.voidGetList(vector<int>&A){
intn=0;
while((n<A.size())&&(cin>>A[n])){ ++n; } A.resize(n);}voidPutList(vector<int>&A){ for(inti=0;i<A.size();++i){ cout<<A[i]<<endl; }}voidGetValues(vector<int>&A){ A.resize(0);
intVal;
while(cin>>Val){ A.push_back(Val); }}StringclassrevisitedvoidGetWords(vector<string>&List){ List.resize(0); strings;
while(cin>>s){ List.push_back(s); }}Ifstandardinputcontained:alistofwordstoberead.thenvector<string>A;GetWords(A);wouldsetAinthemanner:A[0]aA[1]listA[2]ofA[3]wordsA[4]toA[5]beA[6]read.Thefollowingwouldbealsotrue:A[0][0]==‘a(chǎn)’;A[3][2]==‘r’;MultidimensionalarraysintA[3][3]={1,2,3,4,5,6,7,8,9};intB[3][3]={{1,2,3},{4,5,6},{7,8,9}};123456789A[0][0]A[0][1]A[0][2]A[1][0]A[1][1]A[1][2]A[2][0]A[2][1]A[2][2]voidGetWords(charList[][MaxStringSize],
intMaxSize,int&n){
for(n=0;(n<MaxSize)&&(cin>>List[n]);++n){
continue; }}const
intMaxStringSize=10;constintMaxListSize=10;charA[MaxListSize][MaxStringSize];intn;GetWords(A,MaxListSize,n);ThiswouldsetAinthefollowingmanner:A[0]‘a(chǎn)’‘\0’A[1]‘l’‘i’‘s’‘t’‘\0’A[2]‘o’‘f’‘\0’A[3]‘w’‘o’‘r’‘d’‘s’‘\0’A[4]‘t’‘o’‘\0’A[5]‘b’‘e’‘\0’A[6]‘r’‘e’‘a(chǎn)’‘d’‘.’‘\0’A[7]A[8]A[9]alistofwordstoberead.ClickheretoviewsourceCHAPTER11Pointersanddynamicmemorylvalues,rvaluespointertypesnulladdressdereferencingoperator*indirectmemberselectoroperator->addressoperator&pointerassignmentindirectassignmentpointersasparameterspointerstopointersconstantpointersmemberassignmentpointerstoconstantsarraysandpointerscommand-lineparameterspointerstofunctiondynamicobjectsfreestoreoperatorsnewanddeleteexceptionhandlingdanglingpointersmemoryleakdestructorscopyconstructorthispointerKeyConceptsPointerbasicsinti=100,*iPtr=0;charc=‘z’,*s=0;Rational*rPtr=0;iPtr=&i;s=&c;iPtr=i;s=c;indirection(dereferencing)operatoraddressoperatorillegalstatementssciPtri‘z’100intm=0;intn=1;int*Ptr1=&m;int*Ptr2=Ptr1;int*Ptr3=&n;*Ptr1=*Ptr3;Ptr2=Ptr3;Ptr3Ptr2Ptr11n0mPtr3Ptr2Ptr11n1mRationala(4,3);Rational*aPtr=&a;(*aPtr).Insert(cout);aPtr->Insert(cout);Apointerobjectpointstoclass-typeobjects(theselectionoperatorhashigherprecedence)indirectmemberselectoroperatorPointerstopointersint**PtrPtr;inti
=100;int*Ptr=&i;PtrPtr=&Ptr;PtrPtr=Ptr;illegalstatement100PtrPtrPtriExample:pointerscanbeusedto simulatereferenceparametersClicktoviewsourceConstantpointersandpointerstoconstantssuppose:charc1=‘a(chǎn)’;charc2=‘b’;constchar*Ptr1=&c1;charconst*Ptr2=&c1;char*constPtr3=&c2;*Ptr1and*Ptr2areconsideredtobeconstants;Ptr1andPtr2arenotconstant;Ptr3isaconstant;*Ptr3isnotconstantreadthedeclarationsbackwardscharacterstringprocessingcharText[9]=“Bryan”;for(char*Ptr=Text;*Ptr!=‘\0’;++Ptr;){ cout<<Ptr<<endl;}Bryanryanyanannintstrlen(const
chars[]){
inti;
for(i=0;s[i]!=‘\0’;++i){
continue; }
returni;}programcommand-lineparametersbcc32SourceezWin.libe
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 上城區(qū)2025年九年級(jí)下學(xué)期語(yǔ)文學(xué)情調(diào)研試卷(一模)
- 保護(hù)制度熊艷麗模塊三勞動(dòng)保障問(wèn)題協(xié)調(diào)61課件
- 考研復(fù)習(xí)-風(fēng)景園林基礎(chǔ)考研試題附參考答案詳解(綜合題)
- 考研復(fù)習(xí)-風(fēng)景園林基礎(chǔ)考研試題(滿分必刷)附答案詳解
- 風(fēng)景園林基礎(chǔ)考研資料試題及參考答案詳解(研優(yōu)卷)
- 《風(fēng)景園林招投標(biāo)與概預(yù)算》試題A帶答案詳解(能力提升)
- 2025-2026年高校教師資格證之《高等教育法規(guī)》通關(guān)題庫(kù)附答案詳解(培優(yōu)b卷)
- 2023國(guó)家能源投資集團(tuán)有限責(zé)任公司第一批社會(huì)招聘筆試備考題庫(kù)附答案詳解(培優(yōu)b卷)
- 2025福建晉園發(fā)展集團(tuán)有限責(zé)任公司權(quán)屬子公司招聘7人筆試備考題庫(kù)及答案詳解(全優(yōu))
- 2025年黑龍江省五常市輔警招聘考試試題題庫(kù)附答案詳解(完整版)
- 化工廠電氣施工方案
- 2024胃腸間質(zhì)瘤(GIST)診療指南更新解讀
- 重度哮喘診斷與處理中國(guó)專家共識(shí)(2024)解讀
- 成長(zhǎng)類作文“六段式”課件-2024-2025學(xué)年統(tǒng)編版語(yǔ)文九年級(jí)上冊(cè)
- 2024年山東省高考政治+歷史+地理試卷(真題+答案)
- 《區(qū)塊鏈技術(shù)導(dǎo)論》全套教學(xué)課件
- 透析患者控水宣教課件
- 2024年6月浙江高考?xì)v史試卷(含答案)
- 鎮(zhèn)衛(wèi)生院第四期健康教育講座(消除艾滋病、梅毒、乙肝母嬰傳播及防治)
- JJG 746-2024超聲探傷儀
- 2024年湖南省中考數(shù)學(xué)試卷附答案
評(píng)論
0/150
提交評(píng)論