Tải bản đầy đủ - 0 (trang)
Appendix D. Introduction to C++ for Java and C# Programmers

Appendix D. Introduction to C++ for Java and C# Programmers

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

ustoexplorecoreC++conceptssuchascompilationunits,

headerfiles,objectfiles,andlibraries—andtogetfamiliarwith

theC++preprocessor,compiler,andlinker.

Thenwewillturntothemostimportantlanguagedifferences

betweenC++,Java,andC#:howtodefineclasses,howtouse

pointersandreferences,howtooverloadoperators,howtouse

thepreprocessor,andsoon.AlthoughtheC++syntaxis

superficiallysimilartothatofJavaandC#,theunderlying

conceptsdifferinsubtleways.Atthesametime,asan

inspirationalsourceforJavaandC#,theC++languagehasa

lotincommonwiththesetwolanguages,includingsimilardata

types,thesamearithmeticoperators,andthesamebasic

controlflowstatements.

ThelastsectionisdevotedtotheStandardC++library,which

providesready-madefunctionalitythatcanbeusedinanyC++

program.Thelibraryistheresultofmorethanthirtyyearsof

evolution,andassuchitprovidesawiderangeofapproaches

includingprocedural,object-oriented,andfunctional

programmingstyles,andbothmacrosandtemplates.

ComparedwiththelibrariesprovidedwithJavaandC#,the

StandardC++libraryisquitenarrowinscope;forexample,it

hasnosupportforGUIprogramming,multithreading,

databases,internationalization,networking,XML,orUnicode.To

developintheseareas,C++programmersareexpectedtouse

various(oftenplatform-specific)third-partylibraries.

ThisiswhereQtsavestheday.Qtbeganasacross-platform

GUItoolkit(asetofclassesthatmakesitpossibletowrite

portablegraphicaluserinterfaceapplications)butrapidly

evolvedintoafull-blownapplicationdevelopmentframework

thatpartlyextendsandpartlyreplacestheStandardC++

library.AlthoughthisbookusesQt,itisusefultoknowwhatthe

StandardC++libraryhastooffer,sinceyoumayhavetowork

withcodethatusesit.



GettingStartedwithC++



AC++programconsistsofoneormorecompilationunits.Each

compilationunitisaseparatesourcecodefile,typicallywitha

.cppextension(othercommonextensionsare.ccand.cxx)

thatthecompilerprocessesinonerun.Foreachcompilation

unit,thecompilergeneratesanobjectfile,withtheextension

.obj(onWindows)or.o(onUnixandMacOSX).Theobject

fileisabinaryfilethatcontainsmachinecodeforthe

architectureonwhichtheprogramwillrun.

Onceallthe.cppfileshavebeencompiled,wecancombinethe

objectfilestogethertocreateanexecutableusingaspecial

programcalledthelinker.Thelinkerconcatenatestheobject

filesandresolvesthememoryaddressesoffunctionsandother

symbolsreferencedinthecompilationunits.

Whenbuildingaprogram,exactlyonecompilationunitmust

containamain()functionthatservesastheprogram'sentry

point.Thisfunctiondoesn'tbelongtoanyclass;itisaglobal

function.TheprocessisshownschematicallyinFigureD.1.

FigureD.1.TheC++compilationprocess(onWindows)



UnlikeJava,whereeachsourcefilemustcontainexactlyone

class,C++letsusorganizethecompilationunitsaswewant.

Wecanimplementseveralclassesinthesame.cppfile,or

spreadtheimplementationofaclassacrossseveral.cppfiles,

andwecangivethesourcefilesanynameswelike.Whenwe

makeachangeinoneparticular.cppfile,weneedtorecompile

onlythatfileandthenrelinktheapplicationtocreateanew

executable.

Beforewegofurther,let'squicklyreviewthesourcecodeofa



trivialC++programthatcomputesthesquareofaninteger.

Theprogramconsistsoftwocompilationunits:main.cppand

square.cpp.

Here'ssquare.cpp:

1doublesquare(doublen)

2{

3returnn*n;

4}



Thisfilesimplycontainsaglobalfunctioncalledsquare()that

returnsthesquareofitsparameter.

Here'smain.cpp:

1#include

2#include

3doublesquare(double);

4intmain(intargc,char*argv[])

5{

6if(argc!=2){

7std::cerr<<"Usage:square"<
8return1;

9}

10doublen=std::strtod(argv[1],0);

11std::cout<<"Thesquareof"<
12<
13return0;

14}



Themain.cppsourcefilecontainsthemain()function's

definition.InC++,thisfunctiontakesanintandachar*

array(anarrayofcharacterstrings)asparameters.The

program'snameisavailableasargv[0]andthecommand-line

argumentsasargv[1],argv[2],...,argv[argc-1].The

parameternamesargc("argumentcount")andargv

("argumentvalues")areconventional.Iftheprogramdoesn't

accessthecommand-linearguments,wecandefinemain()

withnoparameters.

Themain()functionusesstrtod()("stringtodouble"),cout

(C++'sstandardoutputstream),andcerr(C++'sstandard

errorstream)fromtheStandardC++librarytoconvertthe

command-lineargumenttoadoubleandtoprinttexttothe

console.Strings,numbers,andend-of-linemarkers(endl)are

outputusingthe<
Toaccessthisstandardfunctionality,weneedthe#include

directivesonlines1and2.

AllthefunctionsandmostotheritemsintheStandardC++

libraryareinthestdnamespace.Onewaytoaccessanitemin

anamespaceistoprefixitsnamewiththenamespace'sname

usingthe::operator.InC++,the::operatorseparatesthe

componentsofacomplexname.Namespacesmakelargemultipersonprojectseasierbecausetheyhelpavoidnameconflicts.

Wecoverthemlaterinthisappendix.

Thedeclarationonline3isafunctionprototype.Ittellsthe

compilerthatafunctionexistswiththegivenparametersand

returnvalue.Theactualfunctioncanbelocatedinthesame

compilationunitorinanothercompilationunit.Withoutthe

functionprototype,thecompilerwouldn'tletuscallthefunction

online12.Parameternamesinfunctionprototypesare

optional.

Theproceduretocompiletheprogramvariesfromplatformto

platform.Forexample,tocompileonSolariswiththeSunC++



compiler,wewouldtypethefollowingcommands:

CC-cmain.cpp

CC-csquare.cpp

CCmain.osquare.o-osquare



Thefirsttwolinesinvokethecompilertogenerate.ofilesfor

the.cppfiles.Thethirdlineinvokesthelinkerandgeneratesan

executablecalledsquare,whichwecanrunasfollows:

./square64



Thisrunoftheprogramoutputsthefollowingmessagetothe

console:

Thesquareof64is4096



Tocompiletheprogram,youprobablywanttogethelpfrom

yourlocalC++guru.Failingthis,youcanstillreadtherestof

thisappendixwithoutcompilinganythingandfollowthe

instructionsinChapter1tocompileyourfirstC++/Qt

application.Qtprovidestoolsthatmakeiteasytobuild

applicationsonallplatforms.

Backtoourprogram:Inareal-worldapplication,wewould

normallyputthesquare()functionprototypeinaseparatefile

andincludethatfileinallthecompilationunitswhereweneed

tocallthefunction.Suchafileiscalledaheaderfileandusually

hasa.hextension(.hh,.hpp,and.hxxarealsocommon).If

weredoourexampleusingtheheaderfileapproach,wewould

createafilecalledsquare.hwiththefollowingcontents:

1#ifndefSQUARE_H



2#defineSQUARE_H

3doublesquare(double);

4#endif



Theheaderfileisbracketedbythreepreprocessordirectives

(#ifndef,#define,and#endif).Thesedirectivesensurethat

theheaderfileisprocessedonlyonce,eveniftheheaderfileis

includedseveraltimesinthesamecompilationunit(asituation

thatcanarisewhenheaderfilesincludeotherheaderfiles).By

convention,thepreprocessorsymbolusedtoaccomplishthisis

derivedfromthefilename(inourexample,SQUARE_H).Wewill

comebacktothepreprocessorlaterinthisappendix.

Thenewmain.cppfilelookslikethis:

1#include

2#include

3#include"square.h"

4intmain(intargc,char*argv[])

5{

6if(argc!=2){

7std::cerr<<"Usage:square"<
8return1;

9}

10doublen=std::strtod(argv[1],0);

11std::cout<<"Thesquareof"<
12<
13return0;

14}



The#includedirectiveonline3expandstothecontentsofthe

filesquare.h.Directivesthatstartwitha#arepickedupbythe

C++preprocessorbeforethecompilationpropertakesplace.In

theolddays,thepreprocessorwasaseparateprogramthatthe

programmerinvokedmanuallybeforerunningthecompiler.

Moderncompilershandlethepreprocessorstepimplicitly.

The#includedirectivesonlines1and2expandtothe

contentsofthecstdlibandiostreamheaderfiles,whichare

partoftheStandardC++library.Standardheaderfileshaveno

.hsuffix.Theanglebracketsaroundthefilenamesindicate

thattheheaderfilesarelocatedinastandardlocationonthe

system,anddoublequotestellthecompilertolookinthe

currentdirectory.Includesarenormallygatheredatthetopofa

.cppfile.

Unlike.cppfiles,headerfilesarenotcompilationunitsintheir

ownrightanddonotproduceanyobjectfiles.Headerfilesmay

onlycontaindeclarationsthatenabledifferentcompilationunits

tocommunicatewitheachother.Consequently,itwouldbe

inappropriatetoputthesquare()function'simplementationin

aheaderfile.Ifwedidsoinourexample,nothingbadwould

happen,becauseweincludesquare.honlyonce,butifwe

includedsquare.hfromseveral.cppfiles,wewouldget

multipleimplementationsofthesquare()function(oneper

.cppfilethatincludesit).Thelinkerwouldthencomplainabout

multiple(identical)definitionsofsquare()andrefuseto

generateanexecutable.Conversely,ifwedeclareafunctionbut

neverimplementit,thelinkercomplainsaboutan"unresolved

symbol".

Sofar,wehaveassumedthatanexecutableconsistsexclusively

ofobjectfiles.Inpractice,itoftenalsolinksagainstlibraries

thatimplementready-madefunctionality.Therearetwomain

typesoflibraries:



Staticlibrariesareputdirectlyintotheexecutable,as

thoughtheywereobjectfiles.Thisensuresthatthelibrary

cannotgetlostbutincreasesthesizeoftheexecutable.

Dynamiclibraries(alsocalledsharedlibrariesorDLLs)are

locatedatastandardlocationontheuser'smachineand

areautomaticallyloadedatapplicationstartup.

Forthesquareprogram,welinkagainsttheStandardC++

library,whichisimplementedasadynamiclibraryonmost

platforms.Qtitselfisacollectionoflibrariesthatcanbebuilt

eitherasstaticorasdynamiclibraries(thedefaultisdynamic).



D.IntroductiontoC++forJavaandC#

Programmers

GettingStartedwithC++

MainLanguageDifferences

TheStandardC++Library

ThisappendixprovidesashortintroductiontoC++for

developerswhoalreadyknowJavaorC#.Itassumesthatyou

arefamiliarwithobject-orientedconceptssuchasinheritance

andpolymorphismandthatyouwanttolearnC++.Toavoid

makingthisbookanunwieldy1500pagedoorstopbyincluding

acompleteC++primer,thisappendixconfinesitselfto

essentials.Itpresentsthebasicknowledgeandtechniques

necessarytounderstandtheprogramspresentedintherestof

thebook,withenoughinformationtostartdevelopingcrossplatformC++GUIapplicationsusingQt.

Atthetimeofthiswriting,C++istheonlyrealisticoptionfor

developingcross-platform,high-performance,object-oriented

GUIapplications.ItsdetractorsusuallypointoutthatJavaor

C#,whichdroppedCcompatibility,isnicertouse;infact,

BjarneStroustrup,theinventorofC++,notedinTheDesign

andEvolutionofC++(Addison-Wesley,1994)that"withinC++,

thereisamuchsmallerandcleanerlanguagestrugglingtoget

out".

Fortunately,whenweprogramwithQt,weusuallysticktoa

subsetofC++thatisveryclosetotheutopianlanguage

envisionedbyStroustrup,leavingusfreetoconcentrateonthe

problemathand.Furthermore,QtextendsC++inseveral

respects,throughitsinnovative"signalsandslots"mechanism,

itsUnicodesupport,anditsforeachkeyword.

Inthefirstsectionofthisappendix,wewillseehowtocombine

C++sourcefilestoobtainanexecutableprogram.Thiswilllead



ustoexplorecoreC++conceptssuchascompilationunits,

headerfiles,objectfiles,andlibraries—andtogetfamiliarwith

theC++preprocessor,compiler,andlinker.

Thenwewillturntothemostimportantlanguagedifferences

betweenC++,Java,andC#:howtodefineclasses,howtouse

pointersandreferences,howtooverloadoperators,howtouse

thepreprocessor,andsoon.AlthoughtheC++syntaxis

superficiallysimilartothatofJavaandC#,theunderlying

conceptsdifferinsubtleways.Atthesametime,asan

inspirationalsourceforJavaandC#,theC++languagehasa

lotincommonwiththesetwolanguages,includingsimilardata

types,thesamearithmeticoperators,andthesamebasic

controlflowstatements.

ThelastsectionisdevotedtotheStandardC++library,which

providesready-madefunctionalitythatcanbeusedinanyC++

program.Thelibraryistheresultofmorethanthirtyyearsof

evolution,andassuchitprovidesawiderangeofapproaches

includingprocedural,object-oriented,andfunctional

programmingstyles,andbothmacrosandtemplates.

ComparedwiththelibrariesprovidedwithJavaandC#,the

StandardC++libraryisquitenarrowinscope;forexample,it

hasnosupportforGUIprogramming,multithreading,

databases,internationalization,networking,XML,orUnicode.To

developintheseareas,C++programmersareexpectedtouse

various(oftenplatform-specific)third-partylibraries.

ThisiswhereQtsavestheday.Qtbeganasacross-platform

GUItoolkit(asetofclassesthatmakesitpossibletowrite

portablegraphicaluserinterfaceapplications)butrapidly

evolvedintoafull-blownapplicationdevelopmentframework

thatpartlyextendsandpartlyreplacestheStandardC++

library.AlthoughthisbookusesQt,itisusefultoknowwhatthe

StandardC++libraryhastooffer,sinceyoumayhavetowork

withcodethatusesit.



GettingStartedwithC++



AC++programconsistsofoneormorecompilationunits.Each

compilationunitisaseparatesourcecodefile,typicallywitha

.cppextension(othercommonextensionsare.ccand.cxx)

thatthecompilerprocessesinonerun.Foreachcompilation

unit,thecompilergeneratesanobjectfile,withtheextension

.obj(onWindows)or.o(onUnixandMacOSX).Theobject

fileisabinaryfilethatcontainsmachinecodeforthe

architectureonwhichtheprogramwillrun.

Onceallthe.cppfileshavebeencompiled,wecancombinethe

objectfilestogethertocreateanexecutableusingaspecial

programcalledthelinker.Thelinkerconcatenatestheobject

filesandresolvesthememoryaddressesoffunctionsandother

symbolsreferencedinthecompilationunits.

Whenbuildingaprogram,exactlyonecompilationunitmust

containamain()functionthatservesastheprogram'sentry

point.Thisfunctiondoesn'tbelongtoanyclass;itisaglobal

function.TheprocessisshownschematicallyinFigureD.1.

FigureD.1.TheC++compilationprocess(onWindows)



UnlikeJava,whereeachsourcefilemustcontainexactlyone

class,C++letsusorganizethecompilationunitsaswewant.

Wecanimplementseveralclassesinthesame.cppfile,or

spreadtheimplementationofaclassacrossseveral.cppfiles,

andwecangivethesourcefilesanynameswelike.Whenwe

makeachangeinoneparticular.cppfile,weneedtorecompile

onlythatfileandthenrelinktheapplicationtocreateanew

executable.

Beforewegofurther,let'squicklyreviewthesourcecodeofa



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

Appendix D. Introduction to C++ for Java and C# Programmers

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

×