版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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程序运行的结果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’<‘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’,‘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’;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’‘\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’‘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’;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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 网络安全题库及答案(1000题)
- 2024年纺织品设计与生产许可合同
- 2024年配电箱产品国际标准认证与市场准入合同3篇
- 2024年酒店会议安全保障协议
- 2024年营销策略服务协议标准文本版B版
- 2024投资担保协议-城市更新项目投资合作3篇
- 2024年虚假房产交易借款协议诈骗案版B版
- 2024水电施工全包服务协议样本版B版
- 2024年面料采购协议
- 2024年环保内墙抹灰劳务分包合同(含艺术涂料施工)3篇
- 2023年国家卫生健康委项目资金监管服务中心招聘考试试题及答案
- 期末检测试卷(试题)-2024-2025学年四年级上册数学青岛版
- 2023-2024学年北京市海淀区八年级上学期期末考试物理试卷含详解
- 新人教版七年级上册初中数学全册教材习题课件
- 摔箱测试报告
- 四川省遂宁市城区遂宁市市城区初中2024年第一学期期末教学水平监测七年级历史试题(无答案)
- 建筑垃圾清运投标方案(技术方案)
- JTG F40-2004 公路沥青路面施工技术规范
- JTG D50-2017公路沥青路面设计规范
- 乡镇卫生院管理制度及细则
- 天津市河北区2022-2023学年七年级上学期期末生物试题【带答案】
评论
0/150
提交评论