Tải bản đầy đủ (.pdf) (1,826 trang)

OReilly c plus plus in a nutshell may 2003 ISBN 059600298x

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.5 MB, 1,826 trang )










TableofContents
Index
Reviews
Examples
ReaderReviews
Errata

C++inaNutshell
ByRayLischner

Publisher :O'Reilly
Date
:May2003
Published
ISBN :0-596-00298-X
Pages :808
Slots :1



C++inaNutshellpacksanenormous
amountofinformationonC++(andthe


manylibrariesusedwithit)inan
indispensablequickreferenceforthosewho
liveinadeadline-drivenworldandneedthe
factsbutnotthefrills.Cross-referenceslink
relatedmethods,classes,andotherkey
features.Thisisanidealresourcefor
studentsaswellasprofessional


programmers.











TableofContents
Index
Reviews
Examples
ReaderReviews
Errata

C++inaNutshell
ByRayLischner


Publisher :O'Reilly
Date
:May2003
Published
ISBN :0-596-00298-X
Pages :808
Slots :1

Copyright

Preface
StructureofThisBook

AbouttheExamples




ConventionsUsedinThisBook




CommentsandQuestions

ForMoreInformation
Acknowledgments




Chapter1.LanguageBasics
Section1.1.CompilationSteps

Section1.2.Tokens




Section1.3.Comments



Section1.5.AlternativeTokens

Section1.4.CharacterSets





Section1.6.Trigraphs


Chapter2.Declarations
Section2.1.DeclarationsandDefinitions





Section2.2.Scope




Section2.4.Linkage




Section2.6.ObjectDeclarations

Section2.3.NameLookup
Section2.5.TypeDeclarations
Section2.7.Namespaces



Chapter3.Expressions
Section3.1.LvaluesandRvalues

Section3.2.TypeConversions




Section3.3.ConstantExpressions
Section3.4.ExpressionEvaluation

Section3.5.ExpressionRules




Chapter4.Statements
Section4.1.ExpressionStatements




Section4.2.Declarations




Section4.4.Selections




Section4.6.ControlStatements

Section4.3.CompoundStatements
Section4.5.Loops
Section4.7.HandlingExceptions



Chapter5.Functions
Section5.1.FunctionDeclarations


Section5.2.FunctionDefinitions




Section5.3.FunctionOverloading
Section5.4.OperatorOverloading

Section5.5.ThemainFunction



Chapter6.Classes
Section6.1.ClassDefinitions




Section6.2.DataMembers




Section6.4.Inheritance

Section6.3.MemberFunctions
Section6.5.AccessSpecifiers





Section6.6.Friends

Section6.7.NestedTypes



Chapter7.Templates
Section7.1.OverviewofTemplates




Section7.2.TemplateDeclarations




Section7.4.ClassTemplates




Section7.6.PartialSpecialization




Section7.8.NameLookup


Section7.3.FunctionTemplates
Section7.5.Specialization
Section7.7.Instantiation
Section7.9.TrickswithTemplates

Section7.10.CompilingTemplates



Chapter8.StandardLibrary
Section8.1.OverviewoftheStandardLibrary




Section8.2.CLibraryWrappers




Section8.4.TraitsandPolicies

Section8.3.WideandMultibyteCharacters
Section8.5.Allocators

Section8.6.Numerics



Chapter9.InputandOutput

Section9.1.IntroductiontoI/OStreams




Section9.2.TextI/O




Section9.4.StreamBuffers

Section9.3.BinaryI/O
Section9.5.Manipulators

Section9.6.ErrorsandExceptions



Chapter10.Containers,Iterators,andAlgorithms
Section10.1.Containers




Section10.2.Iterators
Section10.3.Algorithms




Chapter11.PreprocessorReference
#operatoranddirective

##operator



#definedirective




definedoperator




#elifdirective




#endifdirective




#ifdirective





#ifndefdirective




#linedirective

#elsedirective
#errordirective
#ifdefdirective
#includedirective
#pragmadirective

#undefdirective



Chapter12.LanguageReference
andoperator




and_eqoperator





autostorageclass




bitoroperator




breakstatement




catchkeyword




classkeyword




constqualifier





continuestatement




declarator




deleteoperator




doubletype




elsekeyword

asmdefinition
bitandoperator
booltype
casekeyword
chartype
comploperator
const_castoperator
declaration

defaultkeyword
dostatement
dynamic_castoperator
enumkeyword




explicitspecifier




exportspecifier




externstorageclass




floattype




friendspecifier





gotostatement




ifstatement




inttype




mutablespecifier




newoperator




not_eqoperator





oroperator




privateaccessspecifier




publicaccessspecifier




reinterpret_castoperator




shorttype




sizeofoperator





staticstorageclass




structkeyword




templatekeyword

expression
falseliteral
forstatement
function
identifier
inlinespecifier
longtype
namespacekeyword
notoperator
operatorkeyword
or_eqoperator
protectedaccessspecifier
registerstorageclass
returnstatement
signedspecifier

statement
static_castoperator
switchstatement
thiskeyword




throwoperator




trueliteral




type




typeidoperator




unsignedspecifier





usingkeyword




voidkeyword




wchar_ttype




xoroperator

trystatement
typedefkeyword
typenamekeyword
unionkeyword
virtualspecifier
volatilequalifier
whilestatement
xor_eqoperator




Chapter13.LibraryReference
Section13.1.<algorithm>

Section13.2.<bitset>




Section13.3.<cassert>




Section13.5.<cerrno>




Section13.7.<ciso646>




Section13.9.<clocale>




Section13.11.<complex>





Section13.13.<csignal>




Section13.15.<cstddef>




Section13.17.<cstdlib>




Section13.19.<ctime>

Section13.4.<cctype>
Section13.6.<cfloat>
Section13.8.<climits>
Section13.10.<cmath>
Section13.12.<csetjmp>
Section13.14.<cstdarg>
Section13.16.<cstdio>
Section13.18.<cstring>
Section13.20.<cwchar>





Section13.21.<cwctype>




Section13.22.<deque>




Section13.24.<fstream>




Section13.26.<iomanip>




Section13.28.<iosfwd>




Section13.30.<istream>





Section13.32.<limits>




Section13.34.<locale>




Section13.36.<memory>




Section13.38.<numeric>




Section13.40.<queue>




Section13.42.<sstream>





Section13.44.<stdexcept>




Section13.46.<string>




Section13.48.<typeinfo>




Section13.50.<valarray>

Section13.23.<exception>
Section13.25.<functional>
Section13.27.<ios>
Section13.29.<iostream>
Section13.31.<iterator>
Section13.33.<list>
Section13.35.<map>
Section13.37.<new>
Section13.39.<ostream>

Section13.41.<set>
Section13.43.<stack>
Section13.45.<streambuf>
Section13.47.<strstream>
Section13.49.<utility>
Section13.51.<vector>



AppendixA.CompilerExtensions
SectionA.1.BorlandC++BuilderandKylix

SectionA.2.GNUCompilerCollection

SectionA.3.MicrosoftVisualC++



AppendixB.Projects
SectionB.1.Blitz++





SectionB.2.Boost

SectionB.3.STLport




Glossary
A-Z





Colophon
Index


Copyright©2003O'Reilly&Associates,Inc.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'Reilly&Associates,Inc.,1005Gravenstein
HighwayNorth,Sebastopol,CA95472.
O'Reilly&Associatesbooksmaybepurchasedforeducational,
business,orsalespromotionaluse.Onlineeditionsarealso
availableformosttitles().Formore
information,contactourcorporate/institutionalsales
department:(800)998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'Reilly&Associates,
Inc.Manyofthedesignationsusedbymanufacturersand
sellerstodistinguishtheirproductsareclaimedastrademarks.
Wherethosedesignationsappearinthisbook,andO'Reilly&
Associates,Inc.wasawareofatrademarkclaim,the
designationshavebeenprintedincapsorinitialcaps.The
associationbetweentheimageofanEasternchipmunkandthe
topicofC++isatrademarkofO'Reilly&Associates,Inc.

Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.


Preface
C++inaNutshellisareferencetotheC++languageand
library.BeingaNutshellguide,itisnotacomprehensive
manual,butitiscompleteenoughtocovereverythinga
workingprofessionalneedstoknow.Nonetheless,C++issuch
alargeandcomplexlanguagethateventhisNutshellguideisa
largebook.
ThisbookcoverstheC++standard,theinternationalstandard
publishedasISO/IEC14882:1998(E),Programming
LanguagesC++,plusTechnicalCorrigendum1.Many
implementationsofC++extendthelanguageandstandard
library.Exceptforbriefmentionsoflanguageandlibrary
extensionsintheappendixes,thisbookcoversonlythe
standard.Thestandardlibraryislargeitincludesstrings,
containers,commonalgorithms,andmuchmorebutitomits
muchthatiscommonplaceincomputingtoday:concurrency,
networkprotocols,databaseaccess,graphics,windows,andso
on.SeeAppendixBforinformationaboutnonstandardlibraries
thatprovideadditionalfunctionality.
Thisbookisareference.Itisnotatutorial.NewcomerstoC++
mightfindportionsofthisbookdifficulttounderstand.Although
eachsectioncontainssomeadviceonidiomsandtheproper
useofcertainlanguageconstructs,themainfocusisonthe
referencematerial.Visitfor

linkstositesandlistsofbooksthatarebettersuitedfor
beginners.


StructureofThisBook
Thisbookisdividedintotwointerleavedsectionsthatcoverthe
languageandthelibrary,andasectionofappendixes.Roughly
speaking,thelanguageisthepartofC++thatdoesnotrequire
anyadditional#includeheadersorfiles.Thelibraryisthepart
ofC++thatisdeclaredinthestandardheaders.
Chapter1-Chapter7,Chapter11,andChapter12coverthe
language.Thefirstsevenchaptersformthemainlanguage
reference,organizedbytopic.Itiscustomaryfora
programmingreferencetocontainaformalgrammar,andthis
bookdoessoinChapter12,whichisorganizedalphabetically
bykeyword(withsomeadditionalentriesformajorsyntactic
categories,suchasexpressions).Chapter11isareferencefor
thepreprocessor.
Chapter13isthelibraryreference,organizedalphabeticallyby
header.Chapter8-Chapter10presentanoverviewofthelibrary
andintroducethetopicsthatspanindividualheaders.
Sometimes,informationisduplicated,especiallyinChapter12.
Mygoalhasbeentopresentinformationwhenyouneedit,
whereyouneedit.Itriedtobalancetheneedforasingle,clear,
completedescriptionofeachlanguagefeaturewiththedesireto
reducethenumberofcrossreferencesyoumustchasebefore
youcanunderstandthatlanguagefeature.
Herearemoredetaileddescriptionsofeachchapter.
Chapter1describesthebasicrulesfortheC++language:
charactersets,tokens,literals,andsoon.

Chapter2describeshowobjects,types,andnamespacesare
declaredandhownamesarelookedup.


Chapter3describesoperators,precedence,andtypecasts.
Chapter4describesalltheC++statements.
Chapter5describesfunctiondeclarationsanddefinitions,
overloadresolution,argumentpassing,andrelatedtopics.
Chapter6describesclasses(andunionsandstructures),
members,virtualfunctions,inheritance,accessibility,and
multipleinheritance.
Chapter7describesclassandfunctiontemplatedeclarations,
definitions,instantiations,specializations,andhowtemplates
areused.
Chapter8introducesthestandardlibraryanddiscussessome
overarchingtopics,suchastraitsandallocators.
Chapter9introducestheI/Oportionofthestandardlibrary.
TopicsincludeformattedandunformattedI/O,streambuffers,
andmanipulators.
Chapter10introducesthesuiteofcontainerclasstemplates,
theiriterators,andgenericalgorithms.Thisistheportionofthe
librarythathastraditionallybeencalledtheStandardTemplate
Library(STL).
Chapter11isanalphabeticalreferenceforthepreprocessor,
whichispartofthelanguage,butwithadistinctsetofsyntactic
andsemanticrules.
Chapter12isanalphabeticalreferenceforthelanguageand
grammar.Backus-NaurForm(BNF)syntaxdescriptionsare
givenforeachkeywordandotherlanguageelements,with
pointerstothefirstsevenchaptersforthemainreference

material.
Chapter13isareferencefortheentirestandardlibrary,
organizedalphabeticallybyheader,andalphabeticallybyname


withineachheadersection.
AppendixAdescribeswaysthatsomecompilersextendthe
language:tosatisfycustomerneed,tomeetplatform-specific
requirements,andsoon.
AppendixBdescribesafewinteresting,opensourceC++
projects.Youcanfindinformationaboutadditionalprojectson
thisbook'swebsite().
TheGlossarydefinessomewordsandphrasesusedthroughout
thisbookandintheC++community.


AbouttheExamples
Wheneverpossible,theexamplesinthisbookarecomplete,
compilableprograms.Youcantellwhichexamplesfallintothis
categorybecausetheystartwith#includedirectivesand
containamain()function.Youcandownloadtheseexamples
astextfilesfromthebook'swebsiteatorfromO'Reilly'scatalogpageforthisbook:
/>Mostexamplesareshortenedtoeliminateexcesscodethat
mightinterferewiththeclarityoftheexample.Inparticular,
theseexamplesarefragmentsthatlackamainfunction.
Sometimes,anellipsisindicatesmissingcode,suchasa
functionbody.Inothercases,theomissionsareclearfromthe
context.Mostabbreviatedexampleshavecompleteand
compilableversionsavailablefordownload.
Alloftheexampleshavebeencheckedwithseveraldifferent

compilers,includingComeauComputing'scompilerwiththe
Dinkumwarestandardlibrary(widelyacknowledgedasthemost
completeandcorrectimplementationsoftheC++standard).
Notallcompilerscancompilealltheexamplesduetolimitations
andbugsinthecompilersandlibraries.Forbestresults,tryto
workwiththelatestversionofyourcompiler.Recentreleasesof
severalmajorcompilershavemadedramaticprogresstoward
conformancewiththestandard.Whenpossible,Ihavetriedto
altertheexamplefilestoworkaroundthebugswithout
interferingwiththeintentoftheexample.
Ihavecheckedalltheexampleswiththefollowingcompilers:
Linux
BorlandKylix3.0


Comeau4.3.0.1
GNU3.2
Intel7.0
MicrosoftWindows
BorlandC++Builder6.4
MetrowerksCodeWarrior8.3
MicrosoftVisualStudio.NET7.0


ConventionsUsedinThisBook
Thisbookusesthefollowingconventions:
ConstantWidth
Usedforidentifiersandsymbols,includingallkeywords.In
thelanguagereference,constantwidthshowssyntax
elementsthatmustbeusedexactlyasshown.Forexample,

theifkeyword,parentheses,andelsekeywordmustbe
usedexactlyasfollows:
if(condition)statementelsestatement
Afunctionnamethatisfollowedbyparenthesesreferstoa
functioncall,typicallytoobtainthefunctionresult.The
functionnamewithouttheparenthesesreferstothe
functioninmoregeneralterms.Forexample:
Theemptyfunctionreturnstrueifthecontaineris
empty,e.g.,size()==0.
ConstantWidthItalic
Usedinthelanguagereferencechaptersforsyntax
elementsthatmustbereplacedbyyourcode.Inthe
previousexample,youmustsupplytheconditionandthe
twostatements.
ConstantWidthBold
Usedinexamplestohighlightkeylines,andincomplex
declarationstohighlightthenamebeingdeclared.Insome
C++declarations,especiallyfortemplates,thenamegets
buriedinthemiddleofthedeclarationandcanbehardto
spot.


Italic
Usedinthelanguagereferencefornonterminalsyntax
elements.Italicisalsousedforfilenames,URLs,emphasis,
andforthefirstuseofatechnicalterm.
...
Indicatesstatementsanddeclarationsthathavebeen
removedforthesakeofbrevityandclarity.Anellipsisis
alsoasymbolinC++,butcontextandcommentsmakeit

clearwhenanellipsisisalanguageelementandwhenit
representsomittedcode.
[first,last)
Indicatesarangeofvaluesfromfirsttolast,including
firstandexcludinglast.

Thisiconindicatesatip,suggestion,orgeneralnote.

Thisiconindicatesawarningorcaution.

Thisiconindicatesanissueorfeaturethatmightaffectthe
portabilityofyourcode.Inparticular,someaspectsofC++are
implementation-defined,suchasthesizeofaninteger,which
allowsthecompilerorlibraryauthortodecidewhatthebest
implementationshouldbe.


ForMoreInformation
VisittheC++inaNutshellwebsiteattofindlinkstonewsgroups,frequentlyasked
questions,toolandlibrarywebsites,freecompilers,open
sourceprojects,otherC++books,andmore.Thewebsitealso
hasinformationabouttheongoingactivitiesoftheC++
StandardizationCommittee.
Ifyouareagluttonforpunishment,orifyouneedmoredetails
thanareprovidedinthisbook,youmightwanttoreadthe
actualstandard:ISO/IEC14882:1998(E),Programming
LanguagesC++.Thestandardisnoteasytoread,andevenits
authorssometimesdisagreeonitsinterpretation.Nonetheless,
itistheonespecificationfortheC++language,andallother
books,includingthisone,arederivatives,subjecttoerrorand

misinterpretation.TheC++standardlibraryincludestheentire
Cstandardlibrary,whichisdocumentedinISO/IEC9899:1990,
ProgrammingLanguagesC,plusAmendment1:1995(E),C
Integrity.
TheCandC++standardsareevolvingdocuments;the
committeesmeetregularlytoreviewdefectreportsand
proposalsforlanguageextensions.AsIwritethis,theC++
standardcommitteehasapprovedatechnicalcorrigendum
(TC1),whichisanupdatetotheC++standardthatcorrects
defectsandremovesambiguitiesintheoriginalstandard.TC1is
windingitswaythroughtheISObureaucracy.Bythetimeyou
readthis,TC1willhaveprobablycompleteditsjourneyand
beenaddedtotheofficialstandardfortheC++programming
language.Thebook'swebsitehasup-to-dateinformationabout
thestatusoftheC++andCstandards.


CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'Reilly&Associates,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(international/local)
(707)829-0104(fax)
Thereisawebpageforthisbook,whichlistserrata,examples,
oranyadditionalinformation.Youcanaccessthispageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:


Formoreinformationaboutbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seetheO'Reillywebsiteat:



Acknowledgments
Specialthanksgotomytechnicalreviewers:RonNatalie,Uwe
Schnitker,andBruceKrell.Theircorrectionsandsuggestions
havegreatlyimprovedthisbook.
Ipostedearlydraftsofthisbooktomywebsite,andsolicited
comments.DavidCattarinandRoshanNaikwereespecially
helpful.Ithankeveryonewhoalsoprovidedcomments:David
Abrahams,FrankBrown,CyrilleChepelov,JerryCoffin,Buster
Copley,GerhardDoeppert,NicolasFleury,JarrodHollingworth,
JamesKanze,MichaelKochetkov,ClareMacrae,Thomas
Maeder,BrianMcAndrews,JeffRaft,AllanRamacher,Torsten
Robitzki,andJohnSpicer.
ThankstoComeauComputing,Dinkumware,Metrowerks,
Borland,andMicrosoftforgivingmefreeversionsoftheir
compilersandlibrariestousewhilepreparingthisbook.Thanks
alsotoIntelformakingitscompilerfreelyavailabletodownload
forevaluationpurposes.IthankVMwareforlicensestoits
virtualmachinesoftware.
Ithankmyeditor,JonathanGennick,forhispatienceand
advice.
Mostofall,Ithankmywife,Cheryl,andmyson,Arthur,for
theirloveandsupport,withoutwhichIcouldnothavewritten
thisbook.



Chapter1.LanguageBasics
C++isacase-sensitive,free-formprogramminglanguagethat
supportsprocedural,object-oriented,andgenericprogramming.
Thischapterpresentsthebasicrulesforthelanguage,suchas
lexicalrulesandbasicsyntaxelements.


1.1CompilationSteps
AC++sourcefileundergoesmanytransformationsonitsway
tobecominganexecutableprogram.Theinitialstepsinvolve
processingallthe#includeandconditionalpreprocessing
directivestoproducewhatthestandardcallsatranslationunit.
Translationunitsareimportantbecausetheyhaveno
dependenciesonotherfiles.Nonetheless,programmersstill
speakintermsofsourcefiles,eveniftheyactuallymean
translationunits,sothisbookusesthephrasesourcefile
becauseitisfamiliartomostreaders.Theterm"translation"
encompassescompilationandinterpretation,althoughmost
C++translatorsarecompilers.ThissectiondiscusseshowC++
readsandcompiles(translates)sourcefiles(translationunits).
AC++programcanbemadefrommanysourcefiles,andeach
filecanbecompiledseparately.Conceptually,thecompilation
processhasseveralsteps(althoughacompilercanmergeor
otherwisemodifystepsifitcandosowithoutaffectingthe
observableresults):
1. Readphysicalcharactersfromthesourcefileand
translatethecharacterstothesourcecharacterset
(describedinSection1.4laterinthischapter).The
source"file"isnotnecessarilyaphysicalfile;an

implementationmight,forexample,retrievethe
sourcefromadatabase.Trigraphsequencesare
reducedtotheirequivalentcharacters(seeSection
1.6laterinthischapter).Eachnativeend-of-line
characterorcharactersequenceisreplacedbya
newlinecharacter.
Ifabackslashcharacterisfollowedimmediatelybyanewline
character,deletethebackslashandthenewline.The
backslash/newlinecombinationmustnotfallinthemiddleofa


universalcharacter(e.g.,\u1234)andmustnotbeattheend
ofafile.Itcanbeusedinacharacterorstringliteral,orto
continueapreprocessordirectiveorone-linecommenton
multiplelines.Anon-emptyfilemustendwithanewline.
Partitionthesourceintopreprocessortokensseparatedby
whitespaceandcomments.Apreprocessortokenisslightly
differentfromacompilertoken(seethenextsection,Section
1.2).Apreprocessortokencanbeaheadername,identifier,
number,characterliteral,stringliteral,symbol,or
miscellaneouscharacter.Eachpreprocessortokenisthelongest
sequenceofcharactersthatcanmakeupalegaltoken,
regardlessofwhatcomesafterthetoken.
Performpreprocessingandexpandmacros.All#includefiles
areprocessedinthemannerdescribedinsteps1-4.Formore
informationaboutpreprocessing,seeChapter11.
Convertcharacterandstringliteralstotheexecution
characterset.
Concatenateadjacentstringliterals.Narrowstringliteralsare
concatenatedwithnarrowstringliterals.Widestringliteralsare

concatenatedwithwidestringliterals.Mixingnarrowandwide
stringliteralsresultsinanerror.
Performthemaincompilation.
Combinecompiledfiles.Foreachfile,allrequiredtemplate
instantiations(seeChapter7)areidentified,andthenecessary
templatedefinitionsarelocatedandcompiled.
Resolveexternalreferences.Thecompiledfilesarelinkedto
produceanexecutableimage.


×