![C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第1頁](http://file4.renrendoc.com/view/21f5200d8d54d768c1de2b3c7346e203/21f5200d8d54d768c1de2b3c7346e2031.gif)
![C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第2頁](http://file4.renrendoc.com/view/21f5200d8d54d768c1de2b3c7346e203/21f5200d8d54d768c1de2b3c7346e2032.gif)
![C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第3頁](http://file4.renrendoc.com/view/21f5200d8d54d768c1de2b3c7346e203/21f5200d8d54d768c1de2b3c7346e2033.gif)
![C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第4頁](http://file4.renrendoc.com/view/21f5200d8d54d768c1de2b3c7346e203/21f5200d8d54d768c1de2b3c7346e2034.gif)
![C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第5頁](http://file4.renrendoc.com/view/21f5200d8d54d768c1de2b3c7346e203/21f5200d8d54d768c1de2b3c7346e2035.gif)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
IntroductionC++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)Chapter101OverviewofProgrammingWhatIsProgramming?Muchofhumanbehaviorandthoughtischaracterizedbylogicalsequences.Sinceinfancy
youhavebeenlearninghowtobehaveandhowtoperformtasks.Andyouhavelearnedto
expectcertainbehaviorfromotherpeople.OverviewofProgrammingOnthebroadscale,mathematicscouldneverhavebeendevelopedwithoutlogically
sequencedstepsforsolvingproblemsandprovingtheorems.Massproductionwouldnever
haveworkedwithoutoperationstakingplaceinacertainorder.Ourwholecivilizationisbased
ontheorderofthingsandactions.Wecreateorder,bothconsciouslyandunconsciously,throughaprocessthatwecallprogramming.OverviewofProgrammingProgrammingProgrammingisplanninghowtosolveaproblem.Nomatterwhatmethodisusedthe
pencilandpaper,sliderule,addingamachine,orcomputer-problemsolvingrequiresprogramming.Ofcours,howoneprogramdependsonthedeviceoneusesinproblem-solving.OverviewofProgrammingProgramamingisplanningtheperformanceofataskoranevent.Computerprogrammingistheprocessofplanningasequenceofstepsforacomputertofollow.Computerprogramisasequenceofinstructionstobeperformedbyacomputer.OverviewofProgrammingTowriteasequenceofinstructionsforacomputertofollow,wemustgothrougha
three-phaseprocess:problem-solving,implementation,andmaintenance(seeFigure1-1).OverviewofProgrammingUnderstand(define)theproblemandwhatthesolution
mustdo.Analysisandspecification.Developalogicalsequenceofstepsthatsolvesthe
problem.Generalsolution(algorithm).Followthestepsexactlytoseeifthesolutiondoessolvetheproblem.Verify.OverviewofProgrammingAnalgorithmisaverbalorwrittendescriptionofalogicalsequenceofactions(orevents).Afterdevelopingageneralsolution,theprogrammerteststhealgorithm,walkingthrougheach
stepmentallyormanually.Ifthealgorithmdoesnotwork,theprogrammerrepeatsthe
problem-solvingprocess,analyzestheproblemagainandcomesupwithanotheralgorithm.OverviewofProgrammingWhentheprogrammerissatisfiedwiththealgorithm,he/shetranslatesitintoa
programminglanguage.Althoughaprogramminglanguageissimpleinform,itisnotalwayseasytouse.Programmingforcesyoutowriteverysimple,exactinstruction.Translatinganalgorithmintoaprogramminglanguageiscalledcodingthealgorithm.OverviewofProgrammingOnceaprogramhasbeenputintouse,itisoftennecessarytomodifyit.Modificationmay
involvefixinganerrorthatisdiscoveredduringtheuseoftheprogramorchangingthe
programinresponsetochangesintheuser'srequirements.Eachtimetheprogramismodified,itisnecessarytorepeattheproblem-solvingandimplementationphasesforthemodified
aspectsoftheprogram.OverviewofProgrammingThisphaseoftheprogrammingprocessisknownasmaintenanceandactuallyaccountsforthemajorityoftheeffortexpendedonmostprograma.Inaword,theproblem-solving,implementationandmaintenancephasesconstitutetheprogramslifecycle.OverviewofProgramming02ProgrammingMethodologiesProgrammingmethodologydealswiththeanalysis,designandimplementationof
programs.Therearemanyformsofprogrammingmethodology.Thepurposeofmaking
explicitawarenessofprogrammingmethodologyistoallowtheprogrammertobeawareof
theprocessesandprocedureswhichtheyusewhenconstructingprograms.ProgrammingMethodologiesDataAbstractionOneofthekeystosuccessfulprogrammingistheconceptofabstraction.Abstractionis
crucialtobuildingthecomplexsoftwaresystems,Agooddefinitionofabstractioncomesfrom
andcanbesummedupasconcentratingontheaspectsrelevanttotheproblemandignoring
thosethatarenotimportantatthemoment.ProgrammingMethodologiesThepsychologicalnotionofabstractionallowsonetoconcentrateonaproblemata
certainlevelofgeneralizationregardlessoftheirrelevantlow-leveldetails;useofabstraction
alsoallowsonetoworkinanenvironmentwithfamiliarconceptsandtermswithouttheneed
totransformittoanunfamiliarstructure.ProgrammingMethodologiesStructuredProgrammingDividingaproblemintosmallersub-problemsiscalledstructureddesign.Eachsub-problemisthenanalyzedandasolutionisobtainedtosolvethesub-problem.The
solutionstoallsub-problemsarecombinedtosolvetheoverallproblem,Thisprocessof
implementingastructureddesigniscalledstructuredprogramming.ProgrammingMethodologiesThestructured-design
approachisalsoknownasthetop-downdesign,stepwiserefinementandmodular
programming(seeFigure1-2).ProgrammingMethodologiesForusingstructuredprogramming,therearemanygoodreasons:codesareeasierto
understandanderrorsareeasiertofind.Anerrorwillalwaysbelocalizedtoasubroutineor
functionratherthanburiedsomewhereinamassofcode.Thescopeofvariablescanbe
controlledmoreeasily,Withthereuseofcodesaswellasbeingreusedwithinasingl
application,themodularprogrammingallowscodestobeusedinmultipleapplications.Thus.
programsareeasiertodesignthedesignerjustneedstothinkaboutthehigh-levelfunctions.ProgrammingMethodologiesCollaborativeprogrammingispossible--modularprogrammingenablesmorethanone
programmertoworkonasingleapplicationatthesametimewhilethecodescanbestored
acrossmultiplefiles.ProgrammingMethodologiesTheoutputisthesameasabove,butthistimethechanceofthescriptoperationbeing
alteredduetoatypingerrorisgreatlyreduced.Inaddition,ifthereisanerror,thetaskof
correctingitismademuchsimpler.Theprogrammercanalsousethefunctionalitythroughout
theirapplicationwithoutworryingabouthavingtorewritethecode,therebyimprovingthe
codeandthetimeefficiency.ProgrammingMethodologiesStructuredprogramnmingStructuredprogramnmingisaprogrammingparadigmthatenforcesalogicalstructureontheprogrambeingwrittentomakeitmoreelicientandeasiertounderstandandmodifyItisakindoftop-downdesign,stepwiserefinementandmodularprogramming.Itdividesaproblemintoseveralsub-problems,andeachsub-roblemisthenanalyzed,afterward.asolutionisobtainedtosolvethesub-problem.Thesolutionstoallsub-problemsarefnallycombinedtosolvetheoverallproblem.ProgrammingMethodologiesObject-OrientedProgramming(OOP)isawidelyusedprogrammingmethodology.InOOP,thefirststepistoidentifythecomponentscalledobjects,whichformthebasisofthesolution,andtodeterminehowtheseobjectsinteractwithoneanother,asshowninFigure1-3.Thenextstepistospecifyforeachobjecttherelevantdataandpossibleoperationstobeperformedonthedata.Object-OrientedProgrammingProgrammingMethodologiesFipure1-3Object-orientedprogramming.ProgrammingMethodologies03CharacteristicsofObject-OrientedProgrammingObject-orientedprogramming(OOP)isaprogrammingparadigmthatuses“objects”
datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions-to
designapplicationsandcomputerprograms.Programmingtechniquesmayincludefeaturessuchasdataabstraction,encapsulation,polymorphism,andinheritance.Itwasnotcommonly
usedinthemainstreamsoftwareapplicationdevelopmentuntiltheearly1990s.Manymodern
programminglanguagesnowsupportOOP.CharacteristicsofObject-OrientedProgrammingAclassAclassisauser-defineddatatypewhichcontainsvariables,propertiesandmethodsinit.Aclassdefinestheabstractcharacteristicsofathing(object),includingitscharacteristics(itsattributes,fieldsorproperties)andthething'sbehaviors(thethingsitcando,ormethods
operationsorfeatures).Onemightsaythataclassisablueprintorfactorythatdescribesthe
matureofsomething.CharacteristicsofObject-OrientedProgrammingMethodThemethodisasetofproceduralstatementsforachievingthedesiredresult.Itperforms
differentkindsofoperationsondifferentdatatypes.Inaprogramminglanguage,methods
sometimesreferredtoas“functions”)areverbs.Forexample,Lassie,beingaDogobject,has
theabilitytobark.CharacteristicsofObject-OrientedProgrammingMethodSobarkisoneofLassie'smethods.Shemayhaveothermethodsaswell
forexample,sitoreatorwalkorsave.Withintheprogram,usingamethodusuallyaffects
onlyoneparticularobject;alldogscanbark,butyouneedonlyoneparticulardogtodothe
barking.CharacteristicsofObject-OrientedProgrammingMessagepassingistheprocessbywhichanobjectsendsdatatoanotherobjectorasks
theotherobjecttoinvokeamethodwhichisknowntosomeprogramminglanguagesas
interfacing.Forexample,the22啊obiectcalledBreedermaytelltheLassieobjecttositbypassing
a“sit”messagewhichinvokes
Lassie's“sit”method.MessagePassingCharacteristicsofObject-OrientedProgrammingAbstractionisoneofthemostpowerfulandvitalfeaturesprovidedbyobject-oriented
programming.Theconceptofabstractionrelatestotheideaofhidingdatathatarenotneededforthepresentation.Themainideabehinddataabstractionistoclearlyseparatetheproperties
ofdatatypeandtheassociatedimplementationdetails.AbstractionCharacteristicsofObject-OrientedProgrammingEncapsulationEncapsulationconcealsthefunctionaldetailsofaclassfromobjectsthatsendmessages
toit.Forexample,theDogclasshasabarkmethod.Thecodeforthebarkmethoddefines
exactlyhowabarkhappens(e.g,byaninhalemethodandthenanexhalemethod,ata
particularpitchandvolume).Timmy,Lassie'sfiend,however,doesnotneedtoknowexactly
howshebarks.Encapsulationisachievedbyspecifyingwhichclassesmayusethemembersofanobject.CharacteristicsofObject-OrientedProgrammingInheritanceisaprocessinwhichaclassinheritsallthestateandbehaviorofanother
class.Thistypeofrelationshipiscalledchild-parentorisarelationship.“Subclasses”aremore
specializedversionsofaclass,whichinheritattributesandbehaviorsfromtheirparentclasses,andcanintroducetheirown.InheritanceCharacteristicsofObject-OrientedProgrammingForexample,theDogclassmighthavesub-classescalledCollie,Chihuahua,and
GoldenRetriever.Inthiscase,LassiewouldbeaninstanceoftheColliesubclass.Supposethe
DogclassdefinesamethodcalledbarkandapropertycalledfurColor.Eachofitssub-classes
(Collie,Chihuahua,andGoldenRetriever)willinheritthesemembers,meaningthatthe
programmeronlyneedstowritethecodeforthemonce.CharacteristicsofObject-OrientedProgramming04C++ProgrammingLanguage“Aslongastherewerenomachines,programmingwasnoproblematall;whenwehadafewweakcomputers,programmingbecameamildproblemandnowthatwehavegiganticcomputers,programminghasbecomeanequallygiganticproblem,Inthissensetheelectronicindustryhasnotsolvedasingleproblem,ithasonlycreatedthem-ithascreatedtheproblemofusingitsproduct”(E.WDijkstra,TuringAwardLecture,1972).C++ProgrammingLanguageHistoryofCandC++CevolvedfromtwopreviousprogramminglanguageBCPLandB.BCPLwasdevelopedin1967byMartinRichardsasalanguageforwritingoperatingsystemssoftwareandcompilers.KenThompsonmodeledmanyfeaturesinhislanguageBaftertheircounterpartsinBCPLandusedBtocreateearlyversionsoftheUNIXoperatingsystemattheBellLaboratoriesin1970onaDECPDP-7computer.C++ProgrammingLanguageHistoryofCandC++BothBCPLandBwere“typeless”anguage-everydataitemccupiedone“word”inmemorywhiletheburdenoftreatingadata
itemasawholenumberorarealnumber.forexample.fellontheshouldersofthe
programmer.C++ProgrammingLanguageThemostimportantthingtodowhenlearningC++istofocusonconceptsandnotgetlostinlanguage-technicaldetails.Thepurposeoflearningaprogramminglanguageistobecomeabetterprogrammer,thatis,tobecomemoreeffectiveatdesigningandimplementingnewsystemsandatmaintainingoldones.Forthis,theappreciationofprogramminganddesigntechniquesisfarmoreimportantthantheunderstandingofdetails,whichcomeswithtimeandpractice.LearningC++C++ProgrammingLanguageC++supportsavarietyofprogrammingstyles.Allarebasedonstrongstatictypechecking,andmostaimatachievingahighlevelofabstractionandadirectrepresentationoftheprogrammer'sideas.Eachstylecanachieveitsaimseffectivelywhilemaintainingrun-timeandspaceefficiency.C++ProgrammingLanguageAprogrammeroriginallyusingadifferentlanguage(sayC,Fortran,Smalltalk,Pascal,orModula-2)shouldrealizethattogainthebenefitsofC++,theymustspendtimelearningandinternalizingprogrammingstylesandtechniquessuitabletoC++.ThesamesituationappliestoprogrammersusedtoanearlierandlessexpressiveversionofC++.C++ProgrammingLanguageThoughtlesslyapplyingtechniqueseffectiveinonelanguagetoanothertypicallyleadstoawkward,poorlyperforming,andhard-to-maintaincode.Suchcodeisalsomostfrustratingtowritebecauseeverylineofcodeandeverycompilererrormessageremindstheprogrammerthatthelanguageuseddiffersfrom“theoldlanguage”.C++ProgrammingLanguageYoucanwriteinthestyleofFortran,C,Smalltalk,etcinanylanguage,butdoingsoisneitherpleasantnoreconomicalinalanguagewithadifferentphilosophy.EverylanguagecanbeafertilesourceofideasonhowtowriteC++programs.However,ideasmustbetransformedintosomethingthatfitswiththegeneralstructureandtypesystemofC++inordertobeeffectiveindifferentcontexts.C++ProgrammingLanguageC++supportsagradualapproachtolearning.Howyouapproachlearninganewprogramminglanguagedependsonwhatyoualreadyknowandwhatyouamtolearn.Thereisnosingleapproachthatsuitseveryone.MyassumptionisthatyouarelearingC++tobecomeabetterprogrammeranddesigner.Ergo,yourpurposeinlearningC++isnotsimplytolearnanewsyntaxfordoingthingsthewayyouusedto,buttolearnnewandbetterwaysofbuildingsystems.C++ProgrammingLanguageThishastobedonegraduallybecauseacquiringanysignificantnewskilltakestimeandrequirespractice.Considerhowlongitwouldtaketolearnanewnaturallanguagewellortolearntoplayanewmusicalinstrumentwell.Becomingabettersystemdesigneriseasierandfaster,butnotasmucheasierandfasterasmostpeoplewouldlikeittobe.C++ProgrammingLanguage謝謝觀看C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)BasicFacilities—ShiftingfromCtoC++ProgramsC++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)Chapter201C++ProgramStructureTheC++programconsistsofidentifiers,declarations,variables,constants,expressions,statements,andcomments.Acommonstructureforasimple,onefile,C++programincludesthefollowing:Comments.Theydescribeprogramfeature,author,andsoon.C++ProgramStructureIncludestatements.Theyspecifytheheaderfilesforlibraries.Usingnamespacestatement.Typically,thisisonly“usingnamespacestd”.Globaldeclarations(constants,types,variables,…).Avoidglobalvariablesifpossible.C++ProgramStructureFunctionprototypes(declarations).Mainfunctiondefinition.Functiondefinitions.C++ProgramStructureThefollowingexampleisusedtoillustrateaC++programstructure.Donotbetoo
concernedwiththedetailsintheprogram-justobserveitsover-alllookandstructure.C++ProgramStructureAllC++programscompriseoneormorefunctions,whicharealogicalgroupingofone
ormorestatements.Afunctionisidentifiedbyafunctionnameandafunctionbody.C++ProgramStructureAfunctionnameisidentifiedbyawordfollowedbyparentheses.InExample2-1,mainisafunctionname.Allprogramsmusthaveafunctioncalledmain.Theexeeutionofaprogrambeginswiththemainfunction.Thekeywordintalongwiththefunctionnamesignifiesthatthefunctionreturnsanintegervalue.C++ProgramStructureAfunctionbodyissurroundedbycurlybraces({}).Thebracesdelimitablockof
programstatements.Everyfunctionmusthaveapairofbraces.C++ProgramStructure02Input/Output
StreamsAprogramperformsthreebasicoperations:itgetsdata,itmanipulatesthedata,anditoutputtheresults.BecausewritingprogramsforI/Oisquitecomplex,C++offersextensivesupportforI/Ooperations.InC++,I/Oisasequenceofcharacters,calledastream,fromthe
sourcetothedestination.Input/OutputStreamsAstreamisasequenceofcharactersfromthesourcetothedestination.Inputstreamisasequenceofcharactersfromaninputdevice(e.g.keyboard)tothecomputer.Outputstreamisasequenceofcharactersfromthecomputertoanoutputdevice(e.g.monitor).Input/OutputStreamsThestandardlibraryoffersistreamforinput.Theistreamdealswiththecharacterstring
representationsofbuilt-intypesandcaneasilybeextendedtocopewithuser-definedtypes.Withinputstreams,theextractionoperator(>>)isusedtoremovevaluesfromthestream.Thismakessense:whentheuserpressesakeyonthekeyboard,thekeycodeisplacedinan
inputstream.Yourprogramthenextractsthevaluefromthestreamsoitcanbeused.InputStreamInput/OutputStreamsThe>>operator(“getfrom”)isusedasaninputoperator;ein(readsee-in)isoneofthestandardInput/Outputstreams,i.e.iostream.Thetypeoftheright-handoperandof>>determineswhatinputisacceptedandwhatisthetargetoftheinputoperation.Input/OutputStreamsOutputStreamWithoutputstreams,theinsertionoperator(<<)isusedtoputvaluesinthestream.Thisalsomakessense:youinsertyourvaluesintothestream,andthedataconsumer(e.g.monitor)usesthem.Input/OutputStreamsOutputStreamThe<<operator(“putin”)areusedasanoutputoperation.cout(readsee-out)isalsooneofthestandardInput/Outputstreams,i.e.iostream.Bydefault,valuesoutputtocoutareconvertedtoasequenceofcharacters.Input/OutputStreams03ConstantsC++offerstheconceptofauser-definedconstant,aconst,toexpressthenotionthatthevalueofavariablecannotbechangeddirectly.Thisisusefulinseveralcontexts.Forexample,manyvariablesdonotactuallyhavetheirvalueschangedafterinitialization;symbolic
constantsleadtomoremaintainablecodethandoliteralsembeddeddirectlyincode;pointers
areoftenreadthroughbutneverwrittenthrough,andmostfunctionparametersarereadbut
notwrittento.ConstantsTheconstkeywordspecifiesthatavariable'svalueisconstantandtellsthecompilertopreventtheprogrammerfrommodifyingit.Itcanbeaddedtothedeclarationofavariabletodeclarethevariableasaconstant.ConstantsGiventhis,thecompilerknowsthevaluesofclandc2sothattheycanbeusedinconstantexpressions.Sincethevaluesofc3andc4arenotknownatcompiletime,storagemustbeallocatedfore3andc4.Becausetheaddressofc2istaken(andpresumablyusedsomewhere),storagemustbeallocatedforc2.ConstantsPointersandConstantsWhenusingapointer,twovariablesareinvolved:thepointeritselfandthevariablepointedto."Prefixing3thedeclarationofapointerwithconstmakesthevariable,butnotthepointer,aconstant.Todeclareapointeritself,ratherthantheobjectpointedto,tobeaconstant,weusethedeclaratoryoperator*constinsteadofplain*.Constants04FunctionsLetuslookbacktheprograminExample1-3ofChapter1.Whenyouworkonaprogram,itcanbedividedintoafewblockscalledfunetionbody.Sometimes,itisnotpracticaltoputtheentireprogramintoonefunction,e.g.themainfunction,asyouseeinExample1-3.Youmustlearntobreaktheproblemintomanageablepieces.FunctionsFunctionDeclarationsAfunctiondeclarationestablishesthenameofthefunction,thetypeofdatareturnedby
esofitsparameters.FunctionsAfunctiondeclarationconsistsofareturntype,aname,andaparameterlist.Inaddition,afunctiondeclarationmayoptionallyspecifythefunction'slinkage.InC++,thedeclarationcanalsospecifyanexceptionspecification,aconst-qualification,oravolatile-qualification.FunctionsAdeclarationinformsthecompileroftheformatandexistenceofafunctionpriortoitsuse.Afunctioncanbedeclaredseveraltimesinaprogram,providedthatallthedeclarationsarecompatible.Animplicitdeclarationofafunctionisnotallowed:everyfunctionmustbeexplicitlydeclaredbeforeitcanbecalled.FunctionsFunctionDeclarationsAfunctionargument(i.e.actualparameter)isanexpressionoravariablethatyouusewithinthe
parenthesesofafunctioncall.Afunetionparameter(i.e.formalparameter)isanobjeetorreferencedeclared
withintheparenthesisofafunctiondeclarationordefinition.FunctionsFunctionprototypesarerequiredforcompatibilitybetweenCandC++.Thenon-prototypeformofafunctionthathasanemptyparameterlistmeansthatthefunctiontakesanunknownnumberofparametersinC,whereas,inC++,itmeansthatittakesno
parameters.FunctionsFunctionDefinitionsAfunctiondefinitionconsistsofitsname,itsreturntype,itsparameterlistandbody.Thefunctionheaderspecifiesthefunction'sreturntype,nameandparameters.Thefunetionsignatureconsistsofthefunctionnameandtheparameterlist.FunctionsEveryfunctioninaprogrammustbedefinedsomewhere(onceonly)beforeitisinvoked.Afunctiondefinitionisafunctiondeclarationinwhichthebodyofthefunctionispresented.FunctionDefinitionsFunctionsDefaultArgumentsAgeneralfunctionoftenneedsmoreparametersthatarenecessarytohandlesimplecases.Inparticular,functionsthatconstructobjectsoftenprovideseveraloptionsforflexibility.FunctionsAdefaultargumentmeansthatthedefaultvaluesarepassedtotheparameterswhena
functionisinvokedwithoutthearguments.Ofcourse,theusercanchangethedefaultvalueif
heorsheprovidesavalueforthedefaultparameter.FunctionsInlineFunctionsAninlinefunctionisoneforwhichthecompilercopiesthecodefromthefunctiondefinitiondirectlyintothecodeofthecallingfunctionratherthancreatingaseparatesetofinstruetionsinmemory.Insteadoftransferringcontroltoandfromthefunctioncodesegment,amodifiedcopyofthefunctionbodymaysubstitutethefunctiondirectlyforthefunctioncall.Inthisway,theperformaneeoverheadofafunetioncallisavoided.FunctionsFunctionOverloadingMostoften,itisagoodideatogivedifferentfunctions
differentnames,butwhensomefunctionsconceptuallyperformthesametaskonobjectsofdifferenttypes,itcanbemofeconvenienttogivethemthesamename.Usingthesamenameforoperationsondifferenttypesiscalledoverloading.Functions05ReferencesReferenceDefinitionAreferenceisasimplereferencedatatype.Areferenceisanaliasoralternativenameforanobject.ThismeansthatC++allowsyoutocreateasecondnamefortheobjectthatyoucanusetoreadormodifytheoriginaldatastoredintheobject.ReferencesParametersprovideacommunicationlinkbetweenthecallingfunction(suchasmain)andthecalledfunction.Theyenablefunctionstomanipulatedifferentdataeachtimetheyarecalled.Ingeneral,therearetwotypesofformalparameters:valueparametersandreferenceparameters.ReferenceVariablesasParametersReferencesReferencesasReturningValuesReturningvaluesfromafunctiontoitscallerbyvalue,address,orreferenceworksalmost
the
same way
aspassingparameterstoafunction.Theyhavethesameadvantages
and
disadvantages.Theprimarydifferencebetweenthetwoissimplytheoppositedirectionsofdataflow.However,thereisonemoreaddedbitofcomplexity-becauselocalvariablesinafunctiongooutofscopewhenafunctionreturns,weneedtoconsidertheeffectofthisoneachretumtype.ReferencesReturningbyreferenceistypicallyusedtoreturnargumentspassedbyreferencetothe
functionbacktothecallerusedontheright-handsideofanassignmentoperator.Ifthefunctioncallcanappearontheleft-handsideofanassignmentoperator,whatwillhappen?ReferenceasLeft-HandValuesReferences06NamespacesAnamespaceisamechanismforexpressinglogicalgrouping,i.e.ifdeclarationslogically
belongtogetheraccordingtospecificcriteria,thenacommon namespace
expressthisfact.NamespacesInthisexample,variablesa,b,fanddaredeclaredwithintwonamespacescalledmySpaceandyourSpacerespectively.Althoughthesevariableshavethesamename,declaringthemwithinthetwonamespaceswillnotcausearedefinitionerror;thenamespaceisabletoavoidnamecollisions(ofvariables,types,elassesorfunctions).NamespacesHerethefunctionbodiesaredefinedoutsidethenamespacesmySpaeeandyourSpace,theaimof
thisistoseparatetheinterface(ie.funetiondeelaration)fromtheimplementation(i.e.functiondefinition).NamespacesAsaresultofseparatingtheimplementationoftheinterface,eachfunctionnowhasexactlyonedeclarationandonedefinition.Userswillseeonlytheinterfacecontainingdeclarations.Theimplementationinthiscase,thefunctionbodieswillbeplaces“somewhereelse3whereauserdoesnotneedtosee.Namespaces謝謝觀看C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)FoundationofClassesandObjects—DataAbstractionandDefinitionofClassesC++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)Chapter301IntroductiontoStructuresAstructuretypeisauser-definedtype.Structuresareaggregatedatatypebuiltbyusingelementsofothertypes,thatis,structuresareawayofstoringmanydifferentvaluesinvariablesofpotentiallydifferenttypesunderthesamename.Thismakesitamoremodularprogram,whichiseasiertomodifybecauseitsdesignmakesthingsmorecompact.Forexample,astructurecanbeusedtostoreinformationaboutstudentsinadatabase.IntroductiontoStructuresWhenyoudefineastructure,youmustrememberthatthemaindifferencebetweenstructuresandarraysisthatthestruetureisacollectionofdifferentdatatypesandthearrayisacollectionofthesamedatatype.IntroductiontoStructuresDefiningaStructureinC++Theprecedingstructuredefinitiondoesnotreserveanyspaceinmemory,rather,thedefinitioncreatesanewdatatypethatisusedtodeclareavariable.Structure'svariableis
declaredlikevariablesofothertypes.IntroductiontoStructuresTheprogramdefinesasingleDatestructurecalledt
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年二手房交易保障資金協(xié)議
- 2025年雙方自愿解除勞動合同書范例
- 2025年信用卡還款授權(quán)服務(wù)合同
- 2025年中國物流服務(wù)提供商戰(zhàn)略合作協(xié)議
- 海運客運合同法律體系2025年分析
- 2025年企業(yè)債評級擔(dān)保合同標準格式
- 2025年創(chuàng)新知識產(chǎn)權(quán)合資企業(yè)協(xié)議
- 2025年房產(chǎn)遺產(chǎn)繼承人與遺囑執(zhí)行人策劃協(xié)議
- 2025年伙伴間的房產(chǎn)共有合同規(guī)范
- 2025年企業(yè)股權(quán)交易合同樣本(官方版)
- 2025年上半年北京市事業(yè)單位招聘易考易錯模擬試題(共500題)試卷后附參考答案
- 山東省濱州市2024-2025學(xué)年高一上學(xué)期期末考試語文試題(含答案)
- 2025年廣西投資集團有限公司招聘筆試參考題庫含答案解析
- 北京市北師大附中2024-2025學(xué)年高一上學(xué)期期末考試數(shù)學(xué)試卷(含答案)
- 重慶市渝北區(qū)龍山小學(xué)-25版四年級寒假特色作業(yè)【課件】
- 駝鳥養(yǎng)殖生態(tài)旅游項目策劃書方案模版(4篇)
- 煤礦重大災(zāi)害治理中長期規(guī)劃(防治煤塵爆炸、火災(zāi)事故)
- 安全風(fēng)險隱患舉報獎勵制度
- 教學(xué)成果獎培育工作方案
- 廈門三固科技有限公司貨幣資金管理優(yōu)化設(shè)計
- 北京卷2025屆高考語文倒計時模擬卷含解析
評論
0/150
提交評論