C++程序设计英文版_第1页
C++程序设计英文版_第2页
C++程序设计英文版_第3页
C++程序设计英文版_第4页
C++程序设计英文版_第5页
已阅读5页,还剩560页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter1Introduction

C++程序设计课程介绍课程介绍C++语法基础面向对象程序设计的概念大量的编程实践目标熟练掌握C++语法具有面向对象程序设计的概念与能力能熟练阅读复杂的C++程序源代码能独立的设计与完成面向对象的C++程序1.1Whatisacomputerprogram?computerprogram:Acomputerperformsallofthesetasksbyfollowingapredefinedsetofinstructions.computercomputerprogramcookerrecipeprogramminglanguagehigh-levellanguagesNaturelanguagemachinelanguagelow-levellanguagescompiler1.2DevelopingacomputerprogramDevelopingacomputerprogram:defineandunderstandtheproblemtobesolved----Analysisphasehowisittobedone?-----designphasewriting,compilingandtestingC++programs.1.2.1ProgramdevelopmentcycleStep1:Designtheprogram.Eachprogramhastobeindividuallydesignedtoimplementtheoverallsolutiondevelopedattheanalysisanddesignphases.checkitslogicbeforestartingtowritetheprogram1.2DevelopingacomputerprogramStep2:Writetheprogram.theC++programinstructionsaretypedintoafileusingatexteditor

sourcecodeortheprogramcode

sourcefileStep3:Compiletheprogram.translatetheC++programinstructionstomachineinstructionsthroughacompiler--objectcode,andstorestheobjectcodeinanobjectfile.errors----compile-timeerrorsyntaxerror:missingpunctuation,misspellings,…warningmessageisnotasseriousasasyntaxerrorandwillnotpreventtheprogramfrombeingcompiledmaybeaproblemandshouldbeinvestigated1.2DevelopingacomputerprogramStep4:Linktheprogram.combiningtheobjectfileoftheprogramwithotherobjectfilesfromtheC++run-timelibrarytoformanexecutablefileStep5:Testtheprogram.Whentheprogramisrunyoumayfindthatitisnotworkingasexpected.aprogramdoesnothaveanycompile-timeerrorsdoesnotguaranteethattheprogramwillworkasrequiredrun-timeerror—causestheprogramtostopbeforeithascompleteditstasklogicerrors(bugs)---Theprogrammaycompleteitstaskbutproduceincorrectresults1.2DevelopingacomputerprogramStep6:Debugtheprogram.TheprocessoflocatingandcorrectingprogramerrorsiscalleddebuggingManycompilershavetoolsthatcanbeusedtohelplocatebugs.Correctingbugsinvolvesgoingbacktostep2,trytocatcherrorsasearlyaspossible1.2DevelopingacomputerprogramProgramdevelopmentcycleDesignWriteDebugCompileLink提出整体解决方案Test编写C++指令

源文件编译器把C++程序指令转换成机器指令

目标文件链接器将程序目标文件和C++运行时库文件结合

可执行文件定位和修正程序错误确认程序错误(bug)Correct1.3LearningC++AsuccessfulapproachtolearningtoprograminC++dependsonlargeamountsofpractice.exercisesattheendofeachchapter.solutionstoselectedexercisesareatthewebsiteforthisbook.1.4BriefhistoryofC++1972,AT&T,BellLab.DennisRitche,Cprogramminglanguage1980,BellLab.BjarneStroustrup,“CwithClasses”

1983,C++wasdevelopedbyBjarneStrostrupatAT&TBellLaboratories1985,thefirstcommercialversionofC++1997,ANSI(AmericanNationalStandardsInstitute)C++(standardC++)1.6ANSI/ISOC++standard(ANSI/ISOC++标准)TheexampleprogramsusedinthisbookconformtotheANSI/ISOC++standard.Notallcompilersconformtothisstandard,sosomecompilersmaynotcorrectlycompiletheexampleprograms.Someoftheexampleprogramsmayhavetobemodifiedforusewiththeseothercompilers.Seethewebsitefordetails.Chapter2

BeginningtoPrograminC++2.1Constants(常量)DatainC++:Constants;variablesConstants:doesnotchangeitsvalueinaprogram.2.2Variables(变量)Variables:canvaryitsvaluesinaprogramavariablemustbedefinedbeforeitcanbeused.Avariableisdefinedbygivingitadatatypeandanamemain()marksthepointwhereaC++programstartstoexecuteandmustappearonceTheprogramstatementsarecontainedwithinthebraces{and}Eachstatementendswith’;’definesvariables’nameandtypeAssignvaluetovariables2.2VariablesAvariablecanbegivenanyname,calledanidentifier

inC++,provideditiswithinthefollowingrulesAnidentifiercanonlybeconstructedusingletters,numeralsorunderscores(_).Anidentifiermuststartwithaletteroranunderscore.AnidentifiercannotbeaC++keyword.Akeywordisawordthathasaspecialmeaning.

Anidentifiercancontainanynumberofcharacters,butonlythefirstthirty-onecharactersaresignificanttotheC++compiler.Avariableislikeaboxinthememoryofthecomputer.2.3Simpleoutputtothescreencout#include<iostream.h>directivecausesthefiletomakeavailabletotheprogram;<iostream.h>containssomeC++statementstomakeiteasytoperforminputandoutputcout:sendsthedatatocoutthestreaminsertionoperator<<isusedtoinsertastringofcharactersintotheoutputstreamobjectcoutendl:gothestartofthenextlineonthescreenastringofcharacters:lettersornumbersenclosedin“”Thevariablenameisnotinquotationmarks2.4Comments(注释)CommentsareaddedtoaC++programtomakeitmorereadablefortheprogrammercompletelyignoredbythecompiler.commentsstartwiththecharacters//andendattheendoftheline.2.4CommentsC++commentscannotspanmorethanoneline.Typically,commentsareplacedatthestartoftheprogramtodescribethepurposeoftheprogram,theauthor,datewrittenandanyotherrelevantinformationC-stylecommentsbeginwiththecharacters/*andendwiththecharacters*/isalsousedinC++Getintothehabitofusingcommentsbadcommentscanleadtoconfusion2.5Datatypes(数据类型)Differentdatatypesrequiredifferentamountsofmemoryandthereforevaryintherangeofvaluestheycanstore.shortinteger:短整型LongIntegerdatatypes:长整型Booleandatatypes:布尔数据类型canstoreonlyoneoftwovalues:true(1)orfalse(0)DoubleFloating-pointdatatypes:increasetherangeandprecision(oraccuracy)ofafloating-pointnumber.2.6Datatypesizessizeof

operatortodisplaythenumberofbytesofmemoryrequiredbysomecommondatatypes.runningresults2.7Operators(运算符)2.7.1Theassignmentoperator(赋值运算符)“=”assignvaluestovariables.2.7.2Arithmeticoperators(代数运算符)2.7OperatorsProgramExampleP2Erunningresults2.7Operators2.7.3Increment(自加)、decrement(自减)operators++:adds1tothevalueofavariable--:subtracts1fromthevariablevar1Theincrementoperator++hastwoforms,prefixandpostfix2.7OperatorsProgramExampleP2FLine9ofthisprogramdefinesthevariablesvar1andvar2asintegersandinitialisesthemto1and2,respectively.Line15adds1tovar1,andline16subtracts1fromvar2.Lines19and20displaythefinalvalueofvar1andvar2.2.7OperatorsProgramExampleP2G运行结果prefix----Ifthe++isbeforeavariable,thevariableisincrementedbeforeitisused.postfix----Ifthe++isafterthevariable,thevariableisusedandthenincremented.Thedecrementoperator--alsohasprefixandpostfixforms.2.7Operators2.7.4CombinedassignmentoperatorsThe+=operatoraddsthevalueonitsrighttothevariableonitsleft.Therearefivecombinedassignmentoperators:+=,-=,*=,/=,and%=,correspondingtothefivearithmeticoperators+,-,*,/,and%.2.8Operatorprecedence(运算符的优先级)Considerthefollowingstatement:2+7*8=72var2+7*8=58varOperatorprecedence×√1)*,/haveahigherprioritythan+、-2)Expressionscontainingoperatorsofthesameprecedenceareevaluatedaccordingtotheirassociativity3)use()tochangetheorderofevaluation2.8OperatorprecedenceUsingparentheseswillremoveanyconfusionaboutwhichoperationsaredonefirst.unaryminus:“-”appearsbeforeanoperandhighestprioritybinaryminus:appearsbetweentwooperands2.9Typeconversionsandcasts(类型转换和强转)Automaticconversion-----ProgramExampleP2Hrunningresults2.9TypeconversionsandcastsWhendoingcalculationsinvolvingmixeddatatypes,C++ranksthedatatypesinthisorder:promotionorwidening

ofthedataForcalculationsinvolvingmixeddatatypes,C++automaticallyconvertsthevalueinthelowerdatatypetoahighertype.Promotionwillcausenolossofdata,becausethehigherdatatypesoccupymorememorythanthelowertypesandcanthereforeholdthedataprecisely.2.9TypeconversionsandcastsdemotionornarrowingofthedatawhendataisassignedtoavariableofalowertypeDemotionmayresultinalossofdata,becausethelowerdatatypemaynothaveenoughbytesofmemorytostorethehigherdatatype.2.9TypeconversionsandcastsManualconversionwithastaticcastUsingastaticcastisequivalenttoassigningtheexpressiontoavariableofthespecifiedtypeandusingthatvariableinplaceoftheexpression.Theexpressionvar1/4.0ismixed,andthevalueofvar1isthereforepromotedtoafloatingpointvalueautomatically.Programmingpitfalls1.Donottypeasemicolonaftereither2.EndeachC++statementwithasemicolon.3.Asemicolonisnotalwaysattheendofaline.Thiswillcauseacompilererror,becausethesemicolonispartofthecomment.Programmingpitfalls4.Atypingerrormayresultinastatementthatdoesnothingbutthatisvalidnonetheless.Programmingpitfalls5.Youmustinitialiseavariablebeforeusingitinanarithmeticexpression.6.Beawareoftheoperatorprecedencerules.Ifyouareunsure,useparentheses.Thenumberofopeningandclosingparenthesesshouldbeequal.7.Eachvariablehasanassociateddatatype(int,float,etc.).Becarefulnottogooutsidetherangeofvalidvaluesforavariable.Programmingpitfalls8.YoumaynotalwaysgetwhatyouexpectwhendoingarithmeticinC++.variablefwillcontain12,andnotthe12.5Useastaticcastifthefractionalpartoftheresultisrequired.Programmingpitfalls9.Avoidunnecessarycommentsinyourprogram.QuicksyntaxreferenceQuicksyntaxreferenceQ&AThankYou!ThankYou!Chapter3KeyboardInputandScreenOutput

3.1SimpleKeyboardInputDataStreamDatastreamobjectsareusedtoperformbasicinputandoutputofdatatoandfromvariousdevicessuchasthekeyboardandthescreen.Astreamisadatacommunicationobjectconnectedtoaninputoroutputdevice.cout:standardoutputstream

associatedwithSCREEN<<:Theinsertionoperator

isusedtowritedatatocout.cin:standardoutputstreamassociatedwithKEYBOARD>>:Theextractionoperator

isusedtoreaddatafromkeyboad.3.1SimpleKeyboardInputExample:eadsanumberfromthekeyboardandstoresitinthevariablenum3.2Manipulators(流操纵符)Manipulatorsareusedtomodifyinputandoutputdatastreams.endl,setw,setfill,fixed,setprecisionendl:skiptothestartofanewlineonthescreensetw:setthewidthofadatafieldwhichisthenumberofcolumnsthatthedataitemoccupiesonthescreen;setfill:changethe“padding”characterfromaspacetoanyothercharacter.cout<<endl<<endl<<"endlcanbeusedanywhere"<<endl3.2ManipulatorsExample:Howtousemanipulators#include<iomanip>Line4isrequiredforanymanipulator,likesetw,thathasavaluein

parentheses.Ifthefieldwidthissettoosmalltodisplayavalue,thewidthis

automaticallyexpandedsothatallthedigitsinthevaluearedisplayed3.2ManipulatorsExample:Howtousesetfillandsetwsetfillchangethe“padding”characterfromaspaceto“*”setwappliesonlytothenextdataitemintheoutputstreamsetfillremainsineffectforallsubsequentdataitemssenttotheoutputstream.3.2Manipulatorssetprecision:specifythenumberofdigitsofanumbertodisplayThedefaultmaximumnumberofdigitsdisplayedforanumberis6,whichincludesdigitsbeforeandafterthedecimalpoint.Inline12setprecisionsetthetotaldigitstoreservebeforeandafterthedecimalpoint.Inline13withfixedprecedingsetprecisionsetthedigitstoreserveafterthedecimalpointBothmanipulatorsfixedandsetprecisionremainineffectforsubsequentinsertionsintotheoutputstream3.3

Single-characterinputandoutputCharacterInputandOutputWhitespaceCharacters(空白字符):generateaninvisibleblankorwhitespaceonthescreen,suchasTab、Enter

andthespacebar.Inputnoskipws:nomatterwhatitisreadfromkeyboardAlternatively,thefunctionget()associatedwiththeinputstreamobjectcincanbeusedOutputcoutandits<<;theoutputstreamobject

couthasamemberfunctionput()thatcanbeusedtodisplaya

character;3.3

Single-characterinputandoutputExample:Howtoachievesingle-charinput&outputAfunctionisablockofprogramcodethatcarriesoutaspecifictask,whichwillbediscussedinfuture.Readasinglecharacterfromkeyboard(Includingwhitespacecharacters)Programmingpitfalls1.Donotmixuptheinsertionoperator<<andtheextractionoperator>>.Theinsertionoperatorisusedtoinsertdataintotheoutputstream;theextractionoperatorisusedtoreaddatafromtheinputstream.2.Somemanipulatorsapplyonlytothenextdatafield(e.g.setw);others(e.g.setprecision)stayineffectforallsubsequentdatafields.3.Theline#include<iomanip>isrequiredforamanipulatorthathasavalueinparentheses,e.g.setw(4).Othermanipulators,likeendl,donotrequirethisline.QuicksyntaxreferenceQ&AThankYou!ThankYou!Chapter4SelectionandIteration

4.1Selection(选择)sequenceprogramconstructTop-to-bottom:executeonestatementaftertheotherOnlythesimplestofproblemscanbesolvedSelectionanditerationprogramconstructsstatement1statementi…statementnsequenceconstructstatementi+1…selectionconstructiterationconstruct4.1SelectionTheif

statementstartswiththekeywordiffollowedbyanexpressioninparenthesesrelationaloperatorIftheexpressionisfoundtobetrue,thenthestatementfollowingtheifisexecuted.Iftheexpressionisuntrue,thenthestatementfollowingtheifisnotexecuted.4.1SelectionTheif

statement4.1Selection4.1.2Theif-elsestatementWithanif-elsethereischoiceofexecutingoneorotheroftwostatements.if(expression)statemet1elsestatement2truefalsestatement…4.1SelectionProgramExampleP4BIfthevalueofaccount_balanceislessthan0,line14isexecuted;otherwisetheline16isexecuted.4.1Selection4.1.3Compoundstatements(复合语句):Acompoundstatementisoneormorestatementsenclosedinbraces{and}.Thestatementswithinacompoundstatementareusuallyindentedforappearancepurposes.4.1Selection4.1.4LogicaloperatorsThelogicaloperators&&(AND)and||(OR)areusedtocombinetestswithinanifstatement.&&isusedtojointwosimpleconditionstogether;theresultingcompoundconditionisonlytruewhenbothsimpleconditionsaretrue.If||isusedtojointwosimpleconditions,theresultistrueifeitherorbotharetrue.ThelogicalNOToperator!isusedtoreversetheresultofanifstatement.Iftheresultistrue,thenitbecomesfalse,Ifitisfalse,thenitbecomestrue.4.1SelectionLogicaloperators4.1Selection4.1.5Nestedifstatements(嵌套if语句)Whenanifstatementoccurswithinanotherifstatement。4.1Selectionswitch

statementequivalenttoaseriesofif-elsestatementskeyword:switchcase“op”mustbeoftypecharorint.1Thevalueof“op”iscomparedwitheach“case”valueinturn2Statementsfollowing“case”willbeexecutedifmatched3“break”statementterminatestheswitchstatement.4.1Selectionswitch

statementIfnocasematchesthevalueof“OP”,thedefaultcaseisexecuted4.1SelectionTheconditionaloperator条件操作符?:ashortformofif-else.Findsthelargerofnum1andnum24.2Iteration(循环)3iterativecontrolstatementsthewhilestatementthedo-whilestatementtheforstatementThewhilestatementwhile(expression){statement1;…statementn;}otherstatements;ifvalueoftheexpressionistrueotherwise4.2IterationProgramExampleP4FThestatements18~21enclosedwithin{}areexecutedrepeatedlyifthecontrolexpression“num!=0”istrue.Therepeatedexecutionstatementsiscalledaprogramloop.Thesequenceinawhileloop:1.Evaluatethecontrolexpression.2.Ifthecontrolexpressionistrue,executethestatementsintheloopandgobackto1.3.Ifthecontrolexpressionisfalse,exittheloopandexecutethenextstatementaftertheloop.4.2IterationThedo-whileloop1.Executethestatementsintheloop.2.Evaluatethecontrolexpression.3.Ifthecontrolexpressionistruethengobackto1.4.Ifthecontrolexpressionisfalsethenexittheloopandexecutethenextstatementaftertheloop.do{statement1;…statementn;}otherstatements;ifvalueoftheexpressionistrueotherwisewhile(expression)4.2IterationProgramExampleP4G4.2IterationTheforstatementinitialexpression;executedonceatthebeginningoftheloopcontinuecondition;loopcontinueswhiletheitistrue;loopterminateswhenitbecomesfalse;incrementexpressionexecutedattheendofeverypassthroughtheloopfor(“initial”;”continue”;”increment”){statement1;…statementn;}otherstatements;ifvalueof“continue”istrueotherwise4.2IterationProgramExampleP4HThestatements13~17enclosedwithin{}areexecuted5times{}isusedtoclearlyshowthebodyoftheloop.4.2IterationVariationsofProgramExampleP4Hvariableicouldalsobedefinedbeforetheforstatementistartsat10andisdecrementedattheendofeachpassmultipleexpressionsseparatedbycommasintheforstatement4.2IterationAnyorallofthethreeexpressionsmaybeomittedfromaforstatement

;mustalwaysbepresentfor(;;)createaninfiniteloopbecausethereisnoconditiontoendtheloop.4.2IterationNestedloops:WhenaloopiscontainedwithinanotherloopProgramExampleP4ITheloopinlines14~17displaysthenumbers1to12Theloopinlines21~24displaysthe“-”beneaththem4.2IterationNestedloops:WhenaloopiscontainedwithinanotherloopProgramExampleP4ITheouterloop(lines26~33)startswithiat1Line28displaysa|attheleftofthescreenTheinnerloop(lines29~32)isthenexecutedwithjstartingat1andendingwhenjexceeds12.Eachiterationoftheinnerloopdisplaysanumberinthemultiplicationtable.Whentheinnerloopiscompleted,theouterloopregainscontrol,andiisincrementedto2.Programmingpitfalls1.Thereisno;immediatelyafteranifstatement.2.Thereisno;afterswitch.3.Whentestingforequalityuse==,not=.4.Eachelseismatchedwiththepreviousif.5.Foreachopeningbrace{therewillbeaclosingbrace}.Theifonlycontrolstheemptystatementmistakenlymadebythemisplacedsemicolon.Programmingpitfalls6.Bracesarenecessarytocontroltheexecutionofasetofstatementswithanifstatement.7.Thelogicaloperators(&&and||)evaluatethesmallestnumberofoperandsneededtodeterminetheresultofanexpression.Thismeansthatsomeoperandsoftheexpressionmaynotbeevaluated.thestatementa=1isexecutedonlyifaandbareequal.However,thestatementb=2isalwaysexecuted,regardlessofthevaluesofaandb.Programmingpitfalls8.Thereisnosemicolonimmediatelyafterthewhileorforstatements.9.Becarefulinspecifyingtheterminatingconditioninaforloop.asemicolonimmediatelyafterawhileorforstatementmakesthebodyoftheloopemptyThisloopdoesnothing,becausei==10isfalseatthestartoftheloop(iisinfact0)andtheloopterminatesimmediately.Programmingpitfalls10.Thereisnosemicolonafterwhileinawhileloop,butthereisinado-whileloop.11.Thereisalimittotheprecisionwithwhichfloating-pointnumbersarerepresented.Thisisimportantwhentestingafloating-pointnumberforequalityinaniforinaforloop.Onmostcomputersthiswillresultinaninfiniteloop.Thereasonforthisisthatfmayneverequal1.1exactly.QuicksyntaxreferenceQuicksyntaxreferenceQ&AThankYou!ThankYou!Chapter5ArraysandStructures

5.1ArraysArray(数组):agroupofvariablesofthesamedatatypeDefineStoreDimensionofthearray:thenumberofelementsinanarrayArrayindex(orsubscript):ThepositionofanelementinanarrayTheindexofthearraynumbersstartswith05.1ArraysArrayHowtorefertoaparticularelement?usethearraynameandtheindexinbracketsHowtoaccessthefinalelement?or?52×√5.1ArraysProgramExampleP5Adefineagesasanarrayof10integersformat:Theforloopisusedtoreadeachelementofthearrayandaddthemtototal_age.5.1ArraysProgramExampleP5B:findtheminimumandmaximumvaluesinanarraydefineaconstantintegerSIZEandanarray“ages”withsizeSIZEsymbolicconstantTheconstkeywordisusedinthedefinitiontospecifythatitsvaluecannotbechanged.Theidentifierisusuallywritteninuppercase.Usingasymbolicconstantmakestheprogrameasiertomodify5.1ArraysProgramExampleP5B:findtheminimumandmaximumvaluesinanarrayTheforlreadsinvaluesintothearrayagesandtotalsthemoopTheforloopcompareseachelementinthearraywiththevaluesyoungestandoldest.Whenages[i]largerthanoldest,itsvalueisassignedtooldest.Whenages[i]lessthanyoungest,itsvalueisassignedtoyoungest.Thesmallestelementofthearrayisinyoungestandthelargestisinoldestwhentheloopiscompleted.5.1ArraysInitializinganarrayProgramExampleP5CDefineandinitializeanarraydays.Theinitialvaluesinthearrayareseparatedby,andplacedbetween{}.5.1ArraysInitializinganarrayWhenthelistofinitialvaluesislessthanthenumberofelementsinthearray,theremainingelementsareinitializedto0.Ifanarrayisdefinedwithoutspecifyingthenumberofelementsandisinitializedtoaseriesofvalues,thenumberofelementsinthearrayistakentobethesameasthenumberofinitialvalues.||5.1ArraysTwo-dimensionalarraysAtwo-dimensionalarrayhasmorethanonerowofelements5.1ArraysTwo-dimensionalarraysDefine:encloseeachdimensionofthearrayinbracketsAccessanelement:specifytherowandthecolumnTherownumberstartsat0andendsat6Thecolumnnumberstartsat0andendsat4.5.1ArraysProgramExampleP5D:readsinthenumberofstudentsusingthefivelaboratoriesoversevendaysSymbolicconstantNO_OF_DAYSandNO_OF_LABS.

Defineatwo-dimensionalarrayusagewithNO_OF_DAYSrowsandNO_OF_LABScolumns.5.1ArraysProgramExampleP5DTheforlooptotalseverycolumnofarrayusageandaveragethem.Theforloopreadsinvaluesintothearrayusage[][]5.1ArraysInitializingatwo-dimensionalarrayInitializedbyenclosingtheinitialvaluesinbracesPlacetheinitialvaluesofeachrowonaseparatelineoraddbracesineachrowtoimprovereadability

5.1ArraysInitializingatwo-dimensionalarrayOmitthefirstdimensionCompilerwillcalculatethenumberofrowsMissingvaluesareinitializedto0

5.1ArraysMulti-dimensionalarraysDefinearrayswithanynumberofdimensionsTheelementsofthisarrayareaccessedbyusingthreesubscripts5.2Structures5.2.1IntroductionArraysaresuitableforstoringsetsofhomogeneousdataForexample,astudent’stestscoresForitemsofinformationthatarelogicallyrelatedbuteachitemmayhaveadifferentdatatype?Astudent’snumberandtestscoresLogicallyrelateditemsofinformationthatmayhavedifferentdatatypescanbecombinedintoastructure(结构体)5.2Structures5.2.2DeclaringastructureStep1:Declareastructuretemplate:Astructuretemplateconsistsofthereservedkeywordstructfollowedbythenameofthestructure.

structuretag:nameofthestructure

structuremember:eachiteminastructure5.2Structures5.2.2DeclaringastructureStep2:definevariableswiththetypedeclared5.2Structures5.2.2DeclaringastructureAccessmembersofastructurevariable:withthememberselectionoperator“.”ProgramExampleP5E:inputsvaluesforeachmemberofastructureanddisplaysitonthescreen5.2StructuresProgramExampleP5E5.2StructuresProgramExampleP5E5.2StructuresAnotherdeclarationformofastructure5.2Structures5.2.3InitializingastructurevariablePlacetheirinitialvaluesinbracestoinitializeastructure5.2Structures5.2.4NestedstructuresAstructurethatcontainsanotherstructureasoneofitsmembers.5.3Thetypedefstatementtypedefallowstodefineasynonym(同义词)forabuilt-inoraprogrammerdefineddatatypeUsetypedeftodefineasynonymDATEforstructdate:5.4Arraysofstructures(结构体数组)Example:Defineafive-elementarraypersons.Eachelementofthisarrayisofthetypestructpersonnelwithmembersnumber,dobandjoinedThemembersdobandjoinedarethemselvesstructuresandhavemembersday,monthandyear.Whichmemberwillbeaccessed?persons[0].number?persons[4].joined.year?5.5Enumerateddatatypes(枚举数据类型)Anenumerateddatatypeisusedtodescribeasetofintegervalues.Thesestatementsdeclarethedatatyperesponsetohaveoneofthreepossiblevalues:no,yes,ornone.answerisdefinedasanenumeratedvariableoftyperesponse.NameoftheenumerateddatatypedefinedresponseiscalledtheenumerationtagThenamesenclosedin{and}mustbeintegerconstantsThevalueofnois0;thevalueofyesis1;thevalueofnoneis2….5.5Enumerateddatatypes(枚举数据类型)Anotherdefinitionformwhentheenumerateddatatypeandtheenumeratedvariablesaredefinedtogether,theenumerationtagisoptionalArraysofenumerateddatatypeValuesotherthan0,1,and2canalsobeusedProgrammingpitfallsThedimensionsofanarrayareplacedbetweenbrackets[]andnotbetweenparentheses().Therangeofasubscriptis0tothenumberofelementsinanarraylessone.Youcannotcomparestructurevariablesinanifstatement,eveniftheyhavethesamestructuretemplate.ProgrammingpitfallsYoucannotcomparestructurevariablesinanifstatement,eveniftheyhavethesamestructuretemplate.Totests1ands2forequalityyoumusttesteachmemberofeachstructureforequality,asinthestatement×√QuicksyntaxreferenceQ&AThankYou!ThankYou!Chapter6Strings

6.1

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论