C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第1頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第2頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第3頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第4頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)課件全套 ch01Introduction-ch08Templates_第5頁
已閱讀5頁,還剩349頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論