mini C++.docx

上传人:b****3 文档编号:27007698 上传时间:2023-06-25 格式:DOCX 页数:84 大小:81.01KB
下载 相关 举报
mini C++.docx_第1页
第1页 / 共84页
mini C++.docx_第2页
第2页 / 共84页
mini C++.docx_第3页
第3页 / 共84页
mini C++.docx_第4页
第4页 / 共84页
mini C++.docx_第5页
第5页 / 共84页
点击查看更多>>
下载资源
资源描述

mini C++.docx

《mini C++.docx》由会员分享,可在线阅读,更多相关《mini C++.docx(84页珍藏版)》请在冰豆网上搜索。

mini C++.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 初中教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1