关闭

关闭

关闭

封号提示

内容

首页 cs106L_course.pdf

cs106L_course.pdf

cs106L_course.pdf

上传者: memduh 2012-11-02 评分 0 0 0 0 0 0 暂无简介 简介 举报

简介:本文档为《cs106L_coursepdf》,可适用于IT/计算机领域,主题内容包含CourseReaderFallKeithSchwarzStanfordUniversityclassFunctionBase{public:*Po符等。

CourseReaderFallKeithSchwarzStanfordUniversityclassFunctionBase{public:*Polymorphicclassesneedvirtualdestructors*virtual~FunctionBase(){}*Callsthestoredfunction*virtualRetexecute(constArgval)=virtualFunctionBase*clone()const=}*Templatederivedclassthatexecutesaspecifictypeoffunction*template<typenameUnaryFunction>classFunctionImpl:publicFunctionBase{public:explicitFunctionImpl(UnaryFunctionfn):fn(fn){}virtualRetexecute(constArgval){returnfn(val)}virtualFunctionImpl*clone()const{returnnewFunctionImpl(*this)}UnaryFunctionfn}CSLStandardCProgrammingLaboratoryAcknowledgementsThiscoursereaderrepresentstheculminationoftwoyears'workonCSLanditscoursehandoutsNeithertheclassnorthisreaderwouldhavebeenpossiblewithoutJulieZelenski'ssupportandgenerosityduringCSL'sinfancyIstronglyencourageyoutotakeoneofJulie'sclasses–youwillnotbedisappointedI'dalsoliketoextendthankstoalloftheCSLstudentsI'vehadthepleasureofteachingovertheyearsItistrulyajoytowatchstudentslightupwhentheyseeexactlywhatCcandoThelonghoursthatwentintothiscoursereaderwouldnothavebeenpossiblewithouttheknowledgethatstudentsaregenuinelyinterestedinthematerialAdditionally,IwouldliketothankthebravesoulswhoweregenerousenoughtoproofreaddraftversionsofthiscoursereaderYinHuangandStevenWuofferedparticularlyaptadviceonstyleandgrammarIlyaShermangavewonderfulsuggestionsontypesettingandlayoutandcaughtmanyerrorsthatslippedundermyradarKyleKnutsonhelpeddoublecheckthecorrectnessofthecodeintheextendedexamplesDavidGoldblatthelpedmestayontopofrecentdevelopmentsinCxandpointedouthowtomakemanyoftheSTLpracticeproblemstruertothespiritofthelibrarySamSchreiberprovidedexcellentadviceabouttheoverallstructureofthereaderandwastheinspirationforthe“CritiquingClassDesign”chapterLeonidShamisastutelysuggestedthatIexpandthesectionondevelopmentenvironmentsBrittneyFraser'samazingfeedbackmademanyoftheexampleseasiertounderstandandpreventedseveralmajorerrorsfrommakingitintothisreaderThisisthefirsteditionofthiscoursereaderWhilemuchofthecontentistakendirectlyfrompreviousquarters'coursehandouts,overhalfofthiscoursereaderisentirelynewTherearecertainlylayoutproblems,typoz,grammaticallyerrors,andspelingmisstakesthathavemadeitintothisversionIfyouhaveanycomments,corrections,orsuggestions,pleasesendmeanemailathtiekcsstanfordeduThiscoursereaderanditscontents,exceptforquotationsfromothersources,areallKeithSchwarzIfyouwouldliketocopythiscoursereaderoritscontents,sendmeanemailandI'dbegladtoseehowIcanhelpoutTableofContentsIntroductionChapter:WhatisCChapter:GettingStartedChapter:CwithoutgenlibhIntroductiontotheCStandardLibraryChapter:StreamsChapter:STLContainers,PartIChapter:ExtendedExample:SnakeChapter:STLIteratorsChapter:STLContainers,PartIIChapter:ExtendedExample:FiniteAutomataChapter:STLAlgorithmsChapter:ExtendedExample:PalindromesCCoreLanguageFeaturesChapter:PointersandReferencesChapter:CStringsChapter:ThePreprocessorChapter:IntroductiontoTemplatesChapter:constChapter:ExtendedExample:UnionFindChapter:MemberInitializerListsChapter:staticChapter:ConversionConstructorsChapter:CopyConstructorsandAssignmentOperatorsChapter:ExtendedExample:CritiquingClassDesignChapter:OperatorOverloadingChapter:ExtendedExample:SmartPointerChapter:ExtendedExample:DimensionTypeChapter:ExtendedExample:gridChapter:FunctorsChapter:IntroductiontoExceptionHandlingChapter:ExtendedExample:GaussJordanEliminationChapter:IntroductiontoInheritanceChapter:ExtendedExample:FunctionMoretoExploreChapter:CxChapter:WheretoGoFromHereAppendicesAppendix:MovingfromCtoCAppendix:SolutionstoPracticeProblemsBibliographyIndexPartZeroIntroductionSupposewewanttowriteafunctionthatcomputestheaverageofalistofnumbersOneimplementationisgivenhere:doubleGetAverage(doublearr,intnumElems){doubletotal=for(inth=h<numElemsh)total=arrhnumElemsreturntotal}Analternativeimplementationisasfollows:template<typenameForwardIterator>doubleGetAverage(ForwardIteratorbegin,ForwardIteratorend){returnaccumulate(begin,end,)distance(begin,end)}Don'tpanicifyoudon'tunderstandanyofthiscode–you'renotexpectedtoatthispoint–butevenwithoutanunderstandingofhoweitherofthesefunctionsworkit'sclearthattheyareimplementeddifferentlyAlthoughbothofthesefunctionsarevalidCandaccuratelycomputetheaverage,experiencedCprogrammerswilllikelypreferthesecondversiontothefirstbecauseitissafer,moreconcise,andmoreversatileTounderstandwhyyouwouldpreferthesecondversionofthisfunctionrequiresasolidunderstandingoftheCprogramminglanguageNotonlymustyouhaveafirmgraspofhowallthelanguagefeaturesinvolvedineachsolutionwork,butyoumustalsounderstandthebenefitsandweaknessesofeachoftheapproachesandultimatelywhichisamoreversatilesolutionThepurposeofthiscourseistogetyouuptospeedonC'slanguagefeaturesandlibrariestothepointwhereyouarecapableofnotonlywritingCcode,butalsocritiquingyourdesigndecisionsandarguingwhythecocktailoflanguagefeaturesyouchoseisappropriateforyourspecificapplicationThisisanambitiousgoal,butifyoutakethetimetoreadthroughthisreaderandworkoutsomeofthepracticeproblemsyoushouldbeinexcellentCshapeWhothisCourseisForThiscourseisdesignedtoaugmentCSBXbyprovidingaworkingknowledgeofCanditsapplicationsCisanindustrialstrengthtoolthatcanbeharnessedtosolveawidearrayofproblems,andbythetimeyou'vecompletedCSBXandCSLyoushouldbeequippedwiththeskillsetnecessarytoidentifysolutionstocomplexproblems,thentopreciselyandefficientlyimplementthosesolutionsinCThiscoursereaderassumesaknowledgeofCatthelevelatwhichitwouldbecoveredinthefirsttwoweeksofCSBXInparticular,Iassumethatyouarefamiliarwiththefollowing:IntroductionHowtoprinttotheconsole(iecoutandendl)Primitivevariabletypes(int,double,etc)ThestringtypeenumsandstructsFunctionsandfunctionprototypesPassbyvalueandpassbyreferenceControlstructures(if,for,while,do,switch)CSBXspecificlibraries(genlibh,simpioh,theADTs,etc)Ifyouareunfamiliarwithanyoftheseterms,IrecommendreadingthefirstchapterofProgrammingAbstractionsinCbyEricRobertsandJulieZelenski,whichhasanexcellenttreatmentofthematerialTheseconceptsarefundamentaltoCbutaren'tthatparticulartothelanguage–you'llfindsimilarconstructsinC,Java,Python,andotherlanguages–andsoIwon'tdiscussthematgreatlengthInadditiontothelanguageprerequisites,youshouldhaveatleastonequarterofprogrammingexperienceunderyourbelt(CSAshouldbemorethanenough)We'llbewritingalotofcode,andthemoreprogrammingsavvyyoubringtothiscourse,themoreyou'lltakeoutofitHowthisReaderisOrganizedThecoursereaderislogicallydividedintofoursections:Introduction:ThissectionmotivatesandintroducesthematerialandcoversinformationnecessarytobeaworkingCprogrammerInparticular,itfocusesonthehistoryofC,howtosetupaCprojectforcompilation,andhowtomoveawayfromthegenlibhtrainingwheelswe'veprovidedyouinCSBXTheCStandardLibrary:ChasastandardlibrarychockfullofprogramminggoodiesBeforemovingontomoreadvancedlanguagefeatures,we'llexplorewhatthestreamslibraryandSTLhavetoofferCCoreLanguage:CisanenormouslanguagethataffordsgreatflexibilityandcontroloverexactlyhowyourprogramsexecuteThissectiondiscusseswhattoolsareatyourdisposalandprovidesguidelinesfortheirproperusageMoretoExplore:Unfortunately,thiscoursereadercannotcovertheentireCprogramminglanguageThissectionhelpssetupyourjourneyintoCwithadiscussionofthefutureofCandrelevantCresourcesNoticethatthiscoursereaderfocusesonC'sstandardlibrariesbeforeembarkingonadetailedtourofitslanguagefeaturesThismayseembackwards–afterall,howcanyouunderstandlibrarieswritteninalanguageyouhavenotyetstudied–butfromexperienceIbelievethisisthebestwaytolearnCAcomprehensiveunderstandingofthestreamslibraryandSTLrequiresarichunderstandingoftemplates,inheritance,functors,andoperatoroverloading,butevenwithoutknowledgeofthesetechniquesit'sstillpossibletowritenontrivialCprogramsthatusetheselibrariesForexample,afteraquicktourofthestreamslibraryandbasicSTLcontainers,we'llseehowtowriteanimplementationofthegameSnakewithanAIcontrolledplayerLater,oncewe'veexploredtheproperlanguagefeatures,we'llrevisitthestandardlibrariesandseehowthey'reputtogetherTogiveyouafeelforhowClooksinpractice,thiscoursereadercontainstenextendedexamplesthatdemonstratehowtoharnesstheconceptsofthepreviouschapterstosolveaparticularproblemIstronglysuggestthatyoutakethetimetoreadovertheseexamplesandplayaroundwiththecodeTheextendedexamplesshowcasehowtousethetechniquesdevelopedinpreviouschapters,andbyseeinghowthedifferentpiecesofCworktogetheryouwillbeamuchmorecapablecoderInaddition,I'vetriedtoconcludeeachchapterwithafewpracticeproblemsTakeastabatthem–you'llgetamuchmorenuancedviewofthelanguageifyoudoSolutionstosomeofmyfavoriteproblemsaregiveninAppendixOneExerciseswithsolutionsaremarkedwithadiamond()IntroductionCisalargelanguageanditisimpossibletocoverallofitsfeaturesinasinglecourseTohelpguidefurtherexplorationintoCtechniques,mostchapterscontaina“MoretoExplore”sectionlistingimportanttopicsandtechniquesthatmayproveusefulinyourfutureCcareerSupplementalReadingThiscoursereaderisbynomeansacompleteCreferenceandtherearemanylibrariesandlanguagefeaturesthatwesimplydonothavetimetocoverHowever,theportionsofCwedocoverareamongthemostcommonlyusedandyoushouldbeabletopickuptheremainingpiecesonaneedtoknowbasisIfyouareinterestedinamorecompletereferencetext,BjarneStroustrup'sTheCProgrammingLanguage,ThirdEditionisanexcellentchoiceBeawarethatTCPLisnotatutorial–it'sareference–andsoyouwillprobablywanttoreadtherelevantsectionsfromthiscoursereaderbeforedivingintoitIfyou'reinterestedinahybridreferencetutorial,IwouldrecommendCPrimer,FourthEditionbyLippman,Lajoie,andMooAsforonlineresources,theCFAQLiteatwwwparashiftcomcfaqlitehasagreatdiscussionofC'scorelanguagefeaturescpluspluscomhasperhapsthebestcoverageoftheCstandardlibraryontheInternet,thoughitsdiscussionofthelanguageasawholeisfairlylimitedOnwardandForward!Chapter:WhatisCEveryprogramminglanguagehasitsowndistinctflavorinfluencedbyitshistoryanddesignBeforeseriouslystudyingaprogramminglanguage,it'simportanttolearnwhythelanguageexistsandwhatitsobjectivesareThischaptercoversaquickhistoryofC,alongwithsomeofitsdesignprinciplesAnAbbreviatedHistoryofC*ThestoryofCbeginswithBjarneStroustrup,aDanishcomputerscientistworkingtowardhisPhDatCambridgeUniversityForhisresearch,StroustrupdevelopedasimulatorwhichmodeledcomputerscommunicatingoveranetworkStroustrupchosetoworkinalanguagecalledSimula,atthetimeoneoftheforemostobjectorientedprogramminglanguagesAsStroustruprecalled,atfirstSimulaseemedliketheperfecttoolforthejob:ItwasapleasuretowritethatsimulatorThefeaturesofSimulawerealmostidealforthepurpose,andIwasparticularlyimpressedbythewaytheconceptsofthelanguagehelpedmethinkabouttheproblemsinmyapplicationTheclassconceptallowedmetomapmyapplicationconceptsintothelanguageconstructsinadirectwaythatmademycodemorereadablethanIhadseeninanyotherlanguageIhadusedSimulabeforebutwasverypleasantlysurprisedbythewaythemechanismsoftheSimulalanguagebecameincreasinglyhelpfulasthesizeoftheprogramincreasedStrInSimula,itwaspossibletomodelacomputerusingacomputerobjectandanetworkusinganetworkobject,andthewaythatphysicalcomputerssentpacketsoverphysicalnetworkscorrespondedtothewaycomputerobjectssentandreceivedmessagesfromnetworkobjectsButwhileSimulamadeiteasierforStroustruptodevelopthesimulator,theresultingprogramwassoslowthatitfailedtoproduceanymeaningfulresultsThiswasnotthefaultofStroustrup'simplementation,butofSimulaitselfSimulawasbloatedandlanguagefeaturesStroustrupdidn'tuseinhisprogramwerecripplingthesimulator'sefficiencyForexample,Stroustrupfoundthateightypercentofhisprogramtimewasbeingspentongarbagecollectiondespitethefactthatthesimulationdidn'tcreateanygarbageStrInotherwords,whileSimulahaddecreasedthetimerequiredtobuildthesimulator,itdramaticallyincreasedthetimerequiredforthesimulatortoexecuteStroustruprealizedthathisSimulabasedsimulatorwasgoingnowhereTocontinuehisresearch,StroustrupscrappedhisSimulaimplementationandrewrotetheprograminalanguageheknewranquicklyandefficiently:BCPLBCPLhassincegonethewayofthedodo,butatthetime

职业精品

用户评论

0/200
    暂无评论

精彩专题

上传我的资料

热门资料

资料评价:

/49
仅支持在线阅读

意见
反馈

返回
顶部