Tải bản đầy đủ - 0 (trang)
Chapter 2. SETTING OUT TO C++

Chapter 2. SETTING OUT TO C++

Tải bản đầy đủ - 0trang

essentialstructureofaC++programandpreviewssome

topicsnotablyfunctionsandclassescoveredinmuchgreater

detailinlaterchapters.(Theideaistointroduceatleastsome

ofthebasicconceptsgraduallyenroutetothegreat

awakeningsthatcomelater.)



C++Initiation

Let'sbeginwithasimpleC++programthatdisplaysa

message.Listing2.1usestheC++cout(pronouncedcee-out)

facilitytoproducecharacteroutput.Thesourcecodeincludes

severalcommentstothereader;theselinesbeginwith//,and

thecompilerignoresthem.C++iscase-sensitive;thatis,it

discriminatesbetweenuppercasecharactersandlowercase

characters.Thismeansyoumustbecarefultousethesame

caseasintheexamples.Forexample,thisprogramusescout.

IfyousubstituteCoutorCOUT,thecompilerrejectsyour

offeringandaccusesyouofusingunknownidentifiers.(The

compileralsoisspelling-sensitive,sodon'ttrykoutorcoot,

either.)Thecppfilenameextensionisacommonwayto

indicateaC++program;youmightneedtouseadifferent

extension,asdescribedinChapter1,"GettingStarted."



Listing2.1myfirst.cpp



//myfirst.cpp--displaysamessage



#include//aPREPROCESSOR



usingnamespacestd;//makedefinitio



intmain()//functionheadi



{//startoffunct

cout<<"ComeupandC++mesometime.";//message



cout<<"\n";//startanewli



return0;//terminatemain



}//endoffunctio



CompatibilityNote

Ifyou'reusinganoldercompiler,youmightneedtouse#include

insteadof#include;inthiscase,youalso

wouldomittheusingnamespacestd;line.Thatis,replace

#include//thewayofthefuture

usingnamespacestd;//ditto



with



#include//incasethefuturehasnotyetarrived

(Someveryoldcompilersuse#includeinsteadof#include

;ifyouhaveacompilerthatold,youshouldgeteithera

newercompileroranolderbook.)Theswitchfromiostream.hto

iostreamisfairlyrecent,and,atthetimeofthiswriting,somevendors

haven'timplementedityet.

Somewindowingenvironmentsruntheprograminaseparatewindow,and

thenautomaticallyclosethewindowwhentheprogramfinishes.As

discussedinChapter1,youcanmakethewindowstayopenuntilyou

strikeakeybyaddingthefollowinglineofcodebeforethereturn

statement:

cin.get();

Forsomeprogramsyoumustaddtwooftheselines.Thiscodecausesthe

programtowaitforakeystroke.You'lllearnmoreaboutthiscodein

Chapter4,"CompoundTypes."



ProgramAdjustments

Youmightfindthatyoumustaltertheexamplesinthisbooktorunon

yoursystem.Thetwomostcommonchangesarethosethefirst

CompatibilityNoteinthischaptermentions.Oneisamatteroflanguage

standards;ifyourcompilerisnotuptodate,youmustinclude

iostream.hinsteadofiostreamandomitthenamespaceline.The

secondisamatteroftheprogrammingenvironment;youmightneedto

addoneortwocin.get()statementstokeeptheprogramoutput

visibleonscreen.Becausetheseadjustmentsapplyequallytoevery

exampleinthisbook,thisCompatibilityNoteistheonlyalerttothem

youget.Don'tforgetthem!FutureCompatibilityNotesalertyouto

otherpossiblealterationsyoumighthavetomake.



Afteryouuseyoureditorofchoicetocopythisprogram(orelse

usethesourcecodefilesfromtheSamsPublishingWebsiteat

www.samspublishing.com),useyourC++compilertocreate

theexecutablecode,asChapter1outlined.Hereistheoutput

fromrunningthecompiledprogram:

ComeupandC++mesometime.



CInputandOutput

Ifyou'reusedtoprogramminginC,seeingcoutinsteadofthe

printf()functionmightcomeasaminorshock.C++can,infact,use

printf(),scanf(),andalltheotherstandardCinputandoutput

functions,providedthatyouincludetheusualCstdio.hfile.Butthisis

aC++book,soyouuseC++'snewinputfacilities,whichimprovein

manywaysupontheCversions.



YouconstructC++programsfrombuildingblockscalled

functions.Typically,youorganizeaprogramintomajortasks,

andthendesignseparatefunctionstohandlethosetasks.The

exampleshowninListing2.1issimpleenoughtoconsistofa

singlefunctionnamedmain().Themyfirst.cppexamplehas

thefollowingelements:

Comments,indicatedbythe//prefix

Apreprocessor#includedirective

Ausingnamespacedirective

Afunctionheading:intmain()

Afunctionbody,delimitedby{and}

AstatementthatusestheC++coutfacilitytodisplaya

message

Areturnstatementtoterminatethemain()function

Let'slookatthesevariouselementsingreaterdetailnow.The

main()functionisagoodplacetostartbecausesomeofthe

featuresthatprecedemain(),suchasthepreprocessor

directive,aresimplertounderstandafteryouseewhatmain()

does.



Themain()Function

Strippedofthetrimmings,thesampleprogramshowninListing



2.1hasthefollowingfundamentalstructure:

intmain()

{

statements

return0;

}

Theselinesstatethatyouhaveafunctioncalledmain(),and

theydescribehowthefunctionbehaves.Togetherthey

constituteafunctiondefinition.Thisdefinitionhastwoparts:

thefirstline,intmain(),whichiscalledthefunctionheading,

andtheportionenclosedinbraces({and}),whichisthe

functionbody.Figure2.1showsthemain()function.The

functionheadingisacapsulesummaryofthefunction's

interfacewiththerestoftheprogram,andthefunctionbody

representsyourinstructionstothecomputeraboutwhatthe

functionshoulddo.InC++eachcompleteinstructioniscalleda

statement.Youmustterminateeachstatementwitha

semicolon,sodon'tomitthesemicolonswhenyoutypethe

examples.



Figure2.1.Themain()function.



Thefinalstatementinmain(),calledareturnstatement,

terminatesthefunction.Youlearnmoreaboutthereturn

statementasyoureadthroughthischapter.



StatementsandSemicolons

Astatementrepresentsacompleteinstructiontoacomputer.To

understandyoursourcecode,acompilerneedstoknowwhenone

statementendsandanotherbegins.Somelanguagesuseastatement

separator.FORTRAN,forexample,usestheendofthelinetoseparate

onestatementfromthenext.Pascalusesasemicolontoseparateone

statementfromthenext.InPascalyoucanomitthesemicolonin

certaincases,suchasafterastatementjustbeforeanEND,whenyou

aren'tactuallyseparatingtwostatements.(Pragmatistsandminimalists

willdisagreeaboutwhethercanimpliesshould.)ButC++,likeC,usesa

terminatorratherthanaseparator.Theterminatoristhesemicolonthat

markstheendofthestatementaspartofthestatementratherthana

markerbetweenstatements.ThepracticalupshotisthatinC++you

nevercanomitthesemicolon.



TheFunctionHeadingasanInterface

RightnowthemainpointtorememberisthatC++syntax

requiresyoutobeginthedefinitionofthemain()functionwith

thisheading:intmain().Thischapterdiscussesthefunction

headingsyntaxinmoredetaillaterwhenitcoversfunctionsin

general,but,forthosewhocan'tputtheircuriosityonhold,

here'sapreview.

Ingeneral,aC++functionisactivated,orcalled,byanother

function,andthefunctionheadingdescribestheinterface

betweenafunctionandthefunctionthatcallsit.Thepart

precedingthefunctionnameiscalledthefunctionreturntype;

itdescribesinformationflowfromafunctionbacktothe

functionthatcallsit.Thepartwithintheparenthesesfollowing

thefunctionnameiscalledtheargumentlistorparameterlist;

itdescribesinformationflowfromthecallingfunctiontothe

calledfunction.Thisgeneralformatisabitconfusingwhenyou

applyittomain(),becauseyounormallydon'tcallmain()from

otherpartsofyourprogram.Typically,however,main()is

calledbystartupcodethatyourcompileraddstoyourprogram

tomediatebetweentheprogramandtheoperatingsystem

(UNIX,WindowsXP,orwhatever).Ineffect,thefunctionheader

describestheinterfacebetweenmain()andtheoperating

system.

Considertheinterfaceformain(),beginningwiththeintpart.

AC++functioncalledbyanotherfunctioncanreturnavalueto

theactivating(calling)function.Thatvalueiscalledareturn

value.Inthiscase,main()canreturnanintegervalue,as

indicatedbythekeywordint.Next,notetheempty

parentheses.Ingeneral,oneC++functioncanpassinformation

toanotherfunctionwhenitcallsthatfunction.Theportionof

thefunctionheadingenclosedinparenthesesdescribesthat

information.Inthiscase,theemptyparenthesesmeanthatthe

main()functiontakesnoinformation,or,intheusual



terminology,main()takesnoarguments.(Tosaythatmain()

takesnoargumentsdoesn'tmeanthatmain()isan

unreasonable,authoritarianfunction.Instead,argumentisthe

termcomputerbuffsusetorefertoinformationpassedfrom

onefunctiontoanother.)

Inshort,theheading

intmain()

statesthatthemain()functioncanreturnanintegervalueto

thefunctionthatcallsitandthatmain()takesnoinformation

fromthefunctionthatcallsit.

ManyexistingprogramsusetheclassicCheadinginstead:

main()//originalCstyle

UnderC,omittingthereturntypeisthesameassayingthatthe

functionistypeint.However,C++isphasingthisusageout.

Youalsocanusethisvariant:

intmain(void)//veryexplicitstyle

Usingthekeywordvoidintheparenthesesisanexplicitwayof

sayingthatthefunctiontakesnoarguments.UnderC++(but

notC),leavingtheparenthesesemptyisthesameasusing

voidintheparentheses.(InC,leavingtheparenthesesempty

meansyouareremainingsilentaboutwhetherornotthereare

arguments.)



Someprogrammersusethisheadingandomitthereturn

statement:

voidmain()

Thisislogicallyconsistent,becauseavoidreturntypemeans

thefunctiondoesn'treturnavalue.Thisvariantworksonmany

systems,but,becauseitisn'tmandatedasanoptionunder

currentstandards,itdoesnotworkonsomesystems.

Finally,theANSI/ISOC++Standardstatesthata

return0;

statementimplicitlyisunderstoodtocomeattheendofthe

main()function(butofnootherfunction)ifyoudon'texplicitly

provideit.



Whymain()byAnyOtherNameIsNottheSame

There'sanextremelycompellingreasontonamethefunctionin

themyfirst.cppprogrammain():youmustdoso.Ordinarily,

aC++programrequiresafunctioncalledmain().(Andnot,by

theway,Main()orMAIN()ormane().Remember,caseand

spellingcount.)Becausethemyfirst.cppprogramhasonly

onefunction,thatfunctionmustbeartheresponsibilityofbeing

main().WhenyourunaC++program,executionalways

beginsatthebeginningofthemain()function.Therefore,if

youdon'thavemain(),youdon'thaveacompleteprogram,

andthecompilerpointsoutthatyouhaven'tdefinedamain()

function.



Thereareexceptions.Forexample,inWindowsprogramming

youcanwriteadynamiclinklibrary(dll)module.Thisiscode

thatotherWindowsprogramscanuse.Becauseadllmoduleis

notastandaloneprogram,itdoesn'tneedamain().Programs

forspecializedenvironments,suchasforacontrollerchipina

robot,mightnotneedamain().Butyourordinarystandalone

programdoesneedamain();thisbooksdiscussesthatsortof

program.



C++Comments

Thedoubleslash(//)introducesaC++comment.Acomment

isaremarkfromtheprogrammertothereaderthatusually

identifiesasectionofaprogramorexplainssomeaspectofthe

code.Thecompilerignorescomments.Afterall,itknowsC++

atleastaswellasyoudo,and,inanycase,it'sincapableof

understandingcomments.Asfarasthecompilerisconcerned,

Listing2.1looksasifitwerewrittenwithoutcomments:

#include

usingnamespacestd;

intmain()

{

cout<<"ComeupandC++mesometime.";

cout<<"\n";

return0;

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 2. SETTING OUT TO C++

Tải bản đầy đủ ngay(0 tr)

×