mini C++.docx
《mini C++.docx》由会员分享,可在线阅读,更多相关《mini C++.docx(84页珍藏版)》请在冰豆网上搜索。
miniC++
C++LanguageTutorial
Bywill,2010-12-13
1.Introduction1
2.Structureofaprogram2
3.VariablesandDataTypes4
4.Constants8
5.Operators9
6.BasicInput/Output15
7.ControlStructures19
8.Functions(I)26
9.Functions(II)30
10.Arrays34
11.CharacterSequences39
12.Pointers41
13.Input/Outputwithfiles49
1.Introduction
C++isastaticallytyped,free-form,multi-paradigm,compiled,general-purposeprogramminglanguage.Itisregardedasa"middle-level"language,asitcomprisesacombinationofbothhigh-levelandlow-levellanguagefeatures.ItwasdevelopedbyBjarneStroustrupstartingin1979atBellLabsasanenhancementtotheClanguageandoriginallynamedCwithClasses.ItwasrenamedC++in1983.
Asoneofthemostpopularprogramminglanguagesevercreated,C++iswidelyusedinthesoftwareindustry.Someofitsapplicationdomainsincludesystemssoftware,applicationsoftware,devicedrivers,embeddedsoftware,high-performanceserverandclientapplications,andentertainmentsoftwaresuchasvideogames.SeveralgroupsprovidebothfreeandproprietaryC++compilersoftware,includingtheGNUProject,Microsoft,IntelandEmbarcaderoTechnologies.C++hasgreatlyinfluencedmanyotherpopularprogramminglanguages,mostnotablyC#andJava.
1.1Structureofthistutorial
Thetutorialisdividedinthirteensectionscoveringonespecifictopiceach.Youcanaccessanysectiondirectlyfromthesectionindexavailable,orbeginthetutorialfromanypointandfollowthelinksatthebottomofeachsection.
Manysectionsincludeexamplesthatdescribetheuseofthenewlyacquiredknowledgeinthechapter.Itisrecommendedtoreadtheseexamplesandtobeabletounderstandeachofthecodelinesthatconstituteitbeforepassingtothenextchapter.
Agoodwaytogainexperiencewithaprogramminglanguageisbymodifyingandaddingnewfunctionalitiesonyourowntotheexampleprogramsthatyoufullyunderstand.Don'tbescaredtomodifytheexamplesprovidedwiththistutorial,that'sthewaytolearn!
1.2Compilers
Theexamplesincludedinthistutorialareall consoleprograms.Thatmeanstheyusetexttocommunicatewiththeuserandtoshowtheirresults.
AllC++compilerssupportthecompilationofconsoleprograms.Checktheuser'smanualofyourcompilerformoreinfoonhowtocompilethem.
2.Structureofaprogram
Thebestwaytostartlearningaprogramminglanguageisbywritingaprogram.Therefore,hereisourfirstprogram:
1
2
3
4
5
6
7
8
9
10
//myfirstprograminC++
#include
usingnamespacestd;
intmain()
{
cout<<"HelloWorld!
";
return0;
}
HelloWorld!
Thefirstpanel(inlightblue)showsthesourcecodeforourfirstprogram.Thesecondone(inlightgray)showstheresultoftheprogramoncecompiledandexecuted.Totheleft,thegreynumbersrepresentthelinenumbers-thesearenotpartoftheprogram,andareshownheremerelyforinformationalpurposes.
Thepreviousprogramisthetypicalprogramthatprogrammerapprenticeswriteforthefirsttime,anditsresultistheprintingonscreenofthe"HelloWorld!
"sentence.ItisoneofthesimplestprogramsthatcanbewritteninC++,butitalreadycontainsthefundamentalcomponentsthateveryC++programhas.Wearegoingtolooklinebylineatthecodewehavejustwritten:
//myfirstprograminC++
Thisisacommentline.Alllinesbeginningwithtwoslashsigns(//)areconsideredcommentsanddonothaveanyeffectonthebehavioroftheprogram.Theprogrammercanusethemtoincludeshortexplanationsorobservationswithinthesourcecodeitself.Inthiscase,thelineisabriefdescriptionofwhatourprogramis.
#include
Linesbeginningwithahashsign(#)aredirectivesforthepreprocessor.Theyarenotregularcodelineswithexpressionsbutindicationsforthecompiler'spreprocessor.Inthiscasethedirective #include tellsthepreprocessortoincludetheiostreamstandardfile.Thisspecificfile(iostream)includesthedeclarationsofthebasicstandardinput-outputlibraryinC++,anditisincludedbecauseitsfunctionalityisgoingtobeusedlaterintheprogram.
usingnamespacestd;
AlltheelementsofthestandardC++libraryaredeclaredwithinwhatiscalledanamespace,thenamespacewiththename std.Soinordertoaccessitsfunctionalitywedeclarewiththisexpressionthatwewillbeusingtheseentities.ThislineisveryfrequentinC++programsthatusethestandardlibrary,andinfactitwillbeincludedinmostofthesourcecodesincludedinthesetutorials.
intmain()
Thislinecorrespondstothebeginningofthedefinitionofthemainfunction.ThemainfunctionisthepointbywhereallC++programsstarttheirexecution,independentlyofitslocationwithinthesourcecode.Itdoesnotmatterwhetherthereareotherfunctionswithothernamesdefinedbeforeorafterit-theinstructionscontainedwithinthisfunction'sdefinitionwillalwaysbethefirstonestobeexecutedinanyC++program.Forthatsamereason,itisessentialthatallC++programshavea main function.
Theword main isfollowedinthecodebyapairofparentheses(()).Thatisbecauseitisafunctiondeclaration:
InC++,whatdifferentiatesafunctiondeclarationfromothertypesofexpressionsaretheseparenthesesthatfollowitsname.Optionally,theseparenthesesmayenclosealistofparameterswithinthem.
Rightaftertheseparentheseswecanfindthebodyofthemainfunctionenclosedinbraces({}).Whatiscontainedwithinthesebracesiswhatthefunctiondoeswhenitisexecuted.
cout<<"HelloWorld!
";
ThislineisaC++statement.Astatementisasimpleorcompoundexpressionthatcanactuallyproducesomeeffect.Infact,thisstatementperformstheonlyactionthatgeneratesavisibleeffectinourfirstprogram.
cout isthenameofthestandardoutputstreaminC++,andthemeaningoftheentirestatementistoinsertasequenceofcharacters(inthiscasethe HelloWorld sequenceofcharacters)intothestandardoutputstream(cout,whichusuallycorrespondstothescreen).
cout isdeclaredinthe iostream standardfilewithinthe std namespace,sothat'swhyweneededtoincludethatspecificfileandtodeclarethatweweregoingtousethisspecificnamespaceearlierinourcode.
Noticethatthestatementendswithasemicoloncharacter(;).ThischaracterisusedtomarktheendofthestatementandinfactitmustbeincludedattheendofallexpressionstatementsinallC++programs(oneofthemostcommonsyntaxerrorsisindeedtoforgettoincludesomesemicolonafterastatement).
return0;
Thereturnstatementcausesthemainfunctiontofinish.returnmaybefollowedbyareturncode(inourexampleisfollowedbythereturncodewithavalueofzero).Areturncodeof0 forthe main functionisgenerallyinterpretedastheprogramworkedasexpectedwithoutanyerrorsduringitsexecution.ThisisthemostusualwaytoendaC++consoleprogram.
Youmayhavenoticedthatnotallthelinesofthisprogramperformactionswhenthecodeisexecuted.Therewerelinescontainingonlycomments(thosebeginningby //).Therewerelineswithdirectivesforthecompiler'spreprocessor(thosebeginningby #).Thentherewerelinesthatbeganthedeclarationofafunction(inthiscase,themainfunction)and,finallylineswithstatements(liketheinsertioninto cout),whichwereallincludedwithintheblockdelimitedbythebraces({})ofthemainfunction.
InC++,theseparationbetweenstatementsisspecifiedwithanendingsemicolon(;)attheendofeachone,sotheseparationindifferentcodelinesdoesnotmatteratallforthispurpose.Wecanwritemanystatementsperlineorwriteasinglestatementthattakesmanycodelines.Thedivisionofcodeindifferentlinesservesonlytomakeitmorelegibleandschematicforthehumansthatmayreadit.
Comments
Commentsarepartsofthesourcecodedisregardedbythecompiler.Theysimplydonothing.Theirpurposeisonlytoallowtheprogrammertoinsertnotesordescriptionsembeddedwithinthesourcecode.
C++supportstwowaystoinsertcomments:
1
2
//linecomment
/*blockcomment*/
Thefirstofthem,knownaslinecomment,discardseverythingfromwherethepairofslashsigns(//)isfounduptotheendofthatsameline.Thesecondone,knownasblockcomment,discardseverythingbetweenthe /* charactersandthefirstappearanceofthe */ characters,withthepossibilityofincludingmorethanoneline.
Wearegoingtoaddcommentstooursecondprogram:
1
2
3
4
5
6
7
8
9
10
11
/*mysecondprograminC++withmorecomments*/
#include
usingnamespacestd;
intmain()
{
cout<<"HelloWorld!
";//printsHelloWorld!
cout<<"I'maC++program";//printsI'maC++program
return0;
}
HelloWorld!
I'maC++program
Ifyouincludecommentswithinthesourcecodeofyourprogramswithoutusingthecommentcharacterscombinations //, /* or */,thecompilerwilltakethemasiftheywereC++expressions,mostlikelycausingoneorseveralerrormessageswhenyoucompileit.
3.VariablesandDataTypes
Theusefulnessofthe "HelloWorld" programsshownintheprevioussectionisquitequestionable.Wehadtowriteseverallinesofcode,compilethem,andthenexecutetheresultingprogramjusttoobtainasimplesentencewrittenonthescreenasresult.Itcertainlywouldhavebeenmuchfastertotypetheoutputsentencebyourselves.However,programmingisnotlimitedonlytoprintingsimpletextsonthescreen.Inordertogoalittlefurtheronandtobecomeabletowriteprogramsthatperformusefultasksthatreallysaveusworkweneedtointroducetheconceptof variable.
LetusthinkthatIaskyoutoretaint