Tải bản đầy đủ - 0 (trang)
Appendix I. CONVERTING TO ANSI/ISO STANDARD C++

Appendix I. CONVERTING TO ANSI/ISO STANDARD C++

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

PreprocessorDirectives

TheC/C++preprocessorprovidesanarrayofdirectives.In

general,C++practiceistousethosedirectivesdesignedto

managethecompilationprocessandtoavoidusingdirectives

asasubstituteforcode.Forexample,the#includedirectiveis

anessentialcomponentformanagingprogramfiles.Other

directives,suchas#ifndefand#endif,letyoucontrolwhether

particularblocksofcodegetcompiled.The#pragmadirective

letsyoucontrolcompiler-specificcompilationoptions.Theseall

areuseful,sometimesnecessary,tools.Youshouldexert

caution,however,whenitcomestothe#definedirective.



UseconstInsteadof#definetoDefineConstants

Symbolicconstantsmakecodemorereadableand

maintainable.Theconstant'snameindicatesitsmeaning,andif

youneedtochangethevalue,youjusthavetochangethe

valueonce,inthedefinition,thenrecompile.Cusedthe

preprocessorforthispurpose:

#defineMAX_LENGTH100

Thepreprocessorthendoesatextsubstitutioninyoursource

code,replacingoccurrencesofMAX_LENGTHwith100priorto

compilation.

TheC++approachistoapplytheconstmodifiertoavariable

declaration:

constintMAX_LENGTH=100;



ThistreatsMAX_LENGTHasaread-onlyint.

Thereareseveraladvantagestotheconstapproach.First,the

declarationexplicitlynamesthetype.For#define,youmust

usevarioussuffixestoanumbertoindicatetypesotherthan

char,int,ordouble;forexample,using100Ltoindicatea

longtypeor3.14Ftoindicateafloattype.Moreimportantly,

theconstapproachcanjustaseasilybeusedwithderived

types:

constintbase_vals[5]={1000,2000,3500,6000,10000};

conststringans[3]={"yes","no","maybe"};

Finally,constidentifiersobeythesamescoperulesas

variables.Thus,youcancreateconstantswithglobalscope,

namednamespacescope,andblockscope.If,say,youdefinea

constantinaparticularfunction,youdon'thavetoworryabout

thedefinitionconflictingwithaglobalconstantusedelsewhere

inaprogram.Forexample,considerthefollowing:

#definen5

constintdz=12;

...

voidfizzle()

{

intn;



intdz;

...

}

Thepreprocessorwillreplace

intn;

with

int5;

andinduceacompilationerror.Thedzdefinedinfizzle(),

however,willbealocalvariable.Also,fizzle(),ifnecessary,

canusethescoperesolutionoperatorandaccesstheconstant

as::dz.

ChasborrowedtheconstkeywordfromC++,buttheC++

versionismoreuseful.Forexample,theC++versionhas

internallinkageforexternalconstvaluesratherthanthe

defaultexternallinkageusedbyvariablesandbytheCconst.

Thismeansthateachfileinaprogramusingaconstneedsthat

constdefinedinthatparticularfile.Thismightsoundlikeextra

work,but,infact,itmakeslifeeasier.Withinternallinkage,you

canplaceconstdefinitionsinaheaderfileusedbyvariousfiles

inaproject.Thatisacompilererrorforexternallinkagebutnot

forinternallinkage.Also,becauseaconstmustbedefinedin

thefileusingit(beinginaheaderfileusedbythatfilesatisfies

therequirement),youcanuseconstvaluesasarraysize

arguments:



constintMAX_LENGTH=100;

...

doubleloads[MAX_LENGTH];

for(inti=0;i
loads[i]=50;

Thiswon'tworkinCbecausethedefiningdeclarationfor

MAX_LENGTHcouldbeinaseparatefileandnotbeavailable

whenthisparticularfileiscompiled.Infairness,itshouldbe

addedthat,inC,youcouldusethestaticmodifiertocreate

constantswithinternallinkage.It'sjustthatC++,bymaking

staticthedefault,requiresonelessthingforyouto

remember.

Incidentally,therevisedCstandard(C99)doesallowyoutouse

aconstasanarraysize,butthearrayistreatedasanewform

ofarray,calledavariablearray,thatisnotpartoftheC++

standard.

The#definedirective,however,stillisusefulaspartofthe

standardidiomforcontrollingwhenaheaderfileiscompiled:

//blooper.h

#ifndef_BLOOPER_H_

#define_BLOOPER_H_

//codegoeshere



#endif

Fortypicalsymbolicconstants,however,getintothehabitof

usingconstinsteadof#define.Anothergoodalternative,

particularlywhenyouhaveasetofrelatedintegerconstants,is

touseenum:

enum{LEVEL1=1,LEVEL2=2,LEVEL3=4,LEVEL4=8};



UseinlineInsteadof#definetoDefineShort

Functions

ThetraditionalCwaytocreatethenear-equivalentofaninline

functionwastousea#definemacrodefinition:

#defineCube(X)X*X*X

Thisleadthepreprocessortodotextsubstitution,withXbeing

replacedbythecorrespondingargumenttoCube():

y=Cube(x);//replacedwithy=x*x*x;

y=Cube(x+z++);//replacedwithx+z++*x+z++*x+z++;

Becausethepreprocessorusestextsubstitutioninsteadoftrue

passingofarguments,usingsuchmacroscanleadto

unexpectedandincorrectresults.Sucherrorcanbereducedby

usinglotsofparenthesesinthemacrotoensurethecorrect

orderofoperations:



#defineCube(X)((X)*(X)*(X))

Eventhis,however,doesn'tdealwithcasessuchasusing

valueslikez++.

TheC++approachofusingthekeywordinlinetoidentify

inlinefunctionsismuchmoredependablebecauseitusestrue

argumentpassing.Furthermore,C++inlinefunctionscanbe

regularfunctionsorclassmethods.

Onepositivefeatureofthe#definemacroisthatitistypeless

soitcanbeusedwithanytypeforwhichtheoperationmakes

sense.InC++youcancreateinlinetemplatestoachievetypeindependentfunctionswhileretainingargumentpassing.

Inshort,useC++inlininginsteadofC#definemacros.



UseFunctionPrototypes

Actually,youdon'thaveachoice.Althoughprototypingis

optionalinC,itismandatoryinC++.Notethatafunctionthat

isdefinedbeforeitsfirstuse,suchasaninlinefunction,serves

asitsownprototype.

Douseconstinfunctionprototypesandheaderswhen

appropriate.Inparticular,useconstwithpointerparameters

andreferenceparametersrepresentingdatathatisnottobe

altered.Notonlydoesthisallowthecompilertocatcherrors

thatchangedata,italsomakesafunctionmoregeneral.That

is,afunctionwithaconstpointerorreferencecanprocess

bothconstandnon-constdata,whileafunctionthatfailsto

useconstwithapointerorreferenceonlycanprocessnonconstdata.



TypeCasts

OneofStroustrup'spetpeevesaboutCisitsundisciplinedtype

castoperator.True,typecastsoftenarenecessary,butthe

standardtypecastistoounrestrictive.Forexample,consider

thefollowingcode:

structDoof

{

doublefeeb;

doublesteeb;

charsgif[10];

};

Doofleam;

short*ps=(short*)&leam;//oldsyntax

int*pi=int*(&leam);//newsyntax

Nothinginthelanguagepreventsyoufromcastingapointerof

onetypetoapointertoatotallyunrelatedtype.

Inaway,thesituationissimilartothatofthegotostatement.

Theproblemwiththegotostatementwasthatitwastoo

flexible,leadingtotwistedcode.Thesolutionwastoprovide

morelimited,structuredversionsofgototohandlethemost

commontasksforwhichgotowasneeded.Thiswasthegenesis

oflanguageelementssuchasforandwhileloopsandifelse



statements.StandardC++providesasimilarsolutionforthe

problemoftheundisciplinedtypecast,namely,restrictedtype

caststohandlethemostcommonsituationsrequiringtype

casts.ThesearethetypecastoperatorsdiscussedinChapter

15,"Friends,Exceptions,andMore":

dynamic_cast

static_cast

const_cast

reinterpret_cast

So,ifyouaredoingatypecastinvolvingpointers,useoneof

theseoperatorsifpossible.Doingsobothdocumentstheintent

ofthecastandprovidescheckingthatthecastisbeingusedas

intended.



BecomeFamiliarwithC++Features

Ifyou'vebeenusingmalloc()andfree(),switchtousingnew

anddeleteinstead.Ifyou'vebeenusingsetjmp()and

longjmp()forerrorhandling,usetry,throw,andcatch

instead.Tryusingthebooltypeforvaluesrepresentingtrue

andfalse.



UsetheNewHeaderOrganization

TheStandardspecifiesnewnamesfortheheaderfiles,as

describedinChapter2,"SettingOuttoC++."Ifyou'vebeen

usingtheold-styleheaderfiles,youshouldchangeoverto

usingthenew-stylenames.Thisisnotjustacosmeticchange

becausethenewversionsmightaddnewfeatures.For

example,theostreamheaderfileprovidessupportforwidecharacterinputandoutput.Italsoprovidesnewmanipulators

suchasboolalphaandfixed(asdescribedinChapter17,

"Input,Output,andFiles").Theseofferasimplerinterfacethan

usingsetf()ortheiomanipfunctionsforsettingmany

formattingoptions.Ifyoudousesetf(),useios_baseinstead

ofioswhenspecifyingconstants;thatis,useios_base::fixed

insteadofios::fixed.Also,thenewheaderfilesincorporate

namespaces.



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

Appendix I. CONVERTING TO ANSI/ISO STANDARD C++

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

×