Tải bản đầy đủ - 0 (trang)
Chapter 16. THE string CLASS AND THE STANDARD TEMPLATE LIBRARY

Chapter 16. THE string CLASS AND THE STANDARD TEMPLATE LIBRARY

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

ofcontainerobjects.STLexemplifiesarecentprogramming

paradigmcalledgenericprogramming.



ThestringClass

Manyprogrammingapplicationsneedtoprocessstrings.C

providessomesupportwithitsstring.h(cstringinC++)

familyofstringfunctions,andmanyearlyC++implementations

providedhome-grownclassestohandlestrings.Chapter12,

"ClassesandDynamicMemoryAllocation,"introducedamodest

Stringclasstoillustratesomeaspectsofclassdesign.

ANSI/ISOC++itselfprovidesamorepowerfulversioncalled

thestringclass.Itissupportedbythestringheaderfile.

(Notethatthestring.handcstringheaderfilessupporttheC

librarystringfunctionsforC-stylestrings,notthestring

class.)Thekeytousingaclassisknowingitspublicinterface,

andthestringclasshasanextensivesetofmethods,including

severalconstructors,overloadedoperatorsforassigningstrings,

concatenatingstrings,comparingstrings,andaccessing

individualelements,aswellasutilitiesforfindingcharacters

andsubstringsinastring,andmore.Inshort,thestringclass

haslotsofstuff.



ConstructingaString

Let'sbeginwithlookingatthestringconstructors.Afterall,

oneofthemostimportantthingstoknowaboutaclassiswhat

youroptionsarewhencreatingobjectsofthatclass.Listing

16.1usesallsixofthestringconstructors(labeledctor,the

traditionalC++abbreviationforconstructor).Table16.1briefly

describestheconstructorsintheorderusedintheprogram.

Theconstructorrepresentationsaresimplifiedinthatthey

concealthefactthatstringreallyisatypedefforatemplate

specializationbasic_stringandthattheyomitan

optionalargumentrelatingtomemorymanagement.(This

aspectisdiscussedlaterthischapterandinAppendixF,"The



StringTemplateClass.")Thetypesize_typeisan

implementation-dependentintegraltypedefinedinthestring

headerfile.Theclassdefinesstring::nposasthemaximum

possiblelengthofthestring.Typically,thiswouldequalthe

maximumvalueofanunsignedint.Also,thetableusesthe

commonabbreviationNBTSfornull-byte-terminatedstring,that

is,thetraditionalCstring,whichisterminatedwithanull

character.



Constructor



Table16.1.stringClassConstructors

Description



string(constchar*s) InitializesstringobjecttoNBTSpointedtobys.

string(size_typen,

charc)



Createsastringobjectofnelements,eachinitializedto

thecharacterc.eachinitializedtothecharacter

Initializesstringobjecttotheobjectstr,startingat

positionposinstrandgoingtoendofstrorusingn

string(conststring&str,string

characters,whichevercomesfirst.

size_typepos=0,size_typen=npos)



string()



Createsadefaultstringobjectof0size.

string(constchar*s, InitializesstringobjecttoNBTSpointedtobysand

size_typen)

continuesforncharactersevenifthatexceedsthesize

oftheNBTS.

Initializesstringobjecttothevaluesintherange

template

[begin,end),wherebeginandendactlikepointersand

specifylocations;therangeincludesbeginandisupto

string(Iterbegin,Iterend)

butnotincludingend.



Theprogramalsousestheoverloaded+=operator,which

appendsonestringtoanother,theoverloaded=operatorfor

assigningonestringtoanother,theoverloaded<
displayingastringobject,andtheoverloaded[]operatorfor

accessinganindividualcharacterinastring.



Listing16.1str1.cpp



//str1.cpp--introducingthestringclass

#include

#include

usingnamespacestd;

//usingstringconstructors



intmain()

{

stringone("LotteryWinner!");//ctor#1

cout<
stringtwo(20,'$');//ctor#2

cout<
stringthree(one);//ctor#3

cout<
one+="Oops!";//overloaded+=

cout<
two="Sorry!Thatwas";

three[0]='P';



stringfour;//ctor#4

four=two+three;//overloaded+,=

cout<
charalls[]="All'swellthatendswell";

stringfive(alls,20);//ctor#5

cout<
stringsix(alls+6,alls+10);//ctor#6

cout<
stringseven(&five[6],&five[10]);//ctor#6again

cout<


return0;

}



CompatibilityNote

Someolderstringimplementationsdonotsupportctor#6.



Hereistheprogram'soutput:

LotteryWinner!

$$$$$$$$$$$$$$$$$$$$

LotteryWinner!

LotteryWinner!Oops!

Sorry!ThatwasPotteryWinner!

All'swellthatends!

well,well...



ProgramNotes

Thestartoftheprogramillustratesthatyoucaninitializea

stringobjecttoaregularC-stylestringanddisplayitusingthe

overloaded<
stringone("LotteryWinner!");//ctor#1

cout<
Thenextconstructorinitializesthestringobjecttwotoastring

consistingof20$characters:

stringtwo(20,'$');//ctor#2



Thecopyconstructorinitializesthestringobjectthreetothe

stringobjectone:

stringthree(one);//ctor#3

Theoverloaded+=operatorappendsthestring"Oops!"tothe

stringone:

one+="Oops!";//overloaded+=

ThisparticularexampleappendsaC-stylestringtoastring

object.However,the+=operatorismultiplyoverloadedsothat

youalsocanappendstringobjectsandsinglecharacters:

one+=two;//appendastringobject(notinprogram)

one+='!';//appendatypecharvalue(notinprogram)

Similarly,the=operatorisoverloadedsothatyoucanassigna

stringobjecttoastringobject,aC-stylestringtoastring

object,orasimplecharvaluetoastringobject:

two="Sorry!Thatwas";//assignaC-stylestring



two=one;//assignastringobject(notinpro



two='?';//assignacharvalue(notinprogra

Overloadingthe[]operator,astheStringexampleinChapter

13,"ClassInheritance,"did,permitsaccesstoindividual



charactersinastringobjectbyusingarraynotation:

three[0]='P';

Adefaultconstructorcreatesanemptystringthatlatercanbe

givenavalue:

stringfour;//ctor#4

four=two+three;//overloaded+,=

Thesecondlineusestheoverloaded+operatortocreatea

temporarystringobjectwhichisthenassigned,usingthe

overloaded=operator,tothefourobject.Asyoumightexpect,

the+operatorconcatenatesitstwooperandsintoasingle

stringobject.Theoperatorismultiplyoverloadedsothe

secondoperandcanbeastringobjectoraC-stylestringora

charvalue.

ThefifthconstructortakesaC-stylestringandanintegeras

arguments,withtheintegerindicatinghowmanycharactersto

copy:

charalls[]="All'swellthatendswell";

stringfive(alls,20);//ctor#5

Here,astheoutputshows,justthefirst20characters("All's

wellthatends")areusedtoinitializethefiveobject.As

Table16.1notes,ifthecharactercountexceedsthelengthof

theC-stylestring,therequestednumberofcharactersarestill

copied.Soreplacing20with40intheaboveexamplewould



resultin15junkcharactersbeingcopiedattheendoffive.

(Thatis,theconstructorwouldinterpretthecontentsin

memoryfollowingthestring"All'swellthatendswell"as

charactercodes.)

Thesixthconstructorhasatemplateargument:

templatestring(Iterbegin,Iterend);

Theintentisthatbeginandendactlikepointerspointingto

twolocationsinmemory.(Ingeneral,beginandendcanbe

iterators,generalizationsofpointersextensivelyusedinthe

STL.)Theconstructorthenusesthevaluesbetweenthe

locationspointedtobybeginandendtoinitializethestring

objectitconstructs.Thenotation[begin,end),borrowedfrom

mathematics,meanstherangeincludesbeginbutdoesn't

includeend.Thatis,endpointstoalocationonepastthelast

valuetobeused.Considerthefollowingstatement:

stringsix(alls+6,alls+10);//ctor#6

Becausethenameofanarrayisapointer,bothalls+6and

alls+10aretypechar*,sothetemplateisusedwithIter

replacedbytypechar*.Thefirstargumentpointstothefirstw

intheallsarray,andthesecondargumentpointstothespace

followingthefirstwell.Thus,sixisinitializedtothestring

"well".Figure16.1showshowtheconstructorworks.



Figure16.1.stringconstructorusingarange.



Nowsupposeyouwanttousethisconstructortoinitializean

objecttopartofanotherstringobject,say,theobjectfive.

Thefollowingdoesnotwork:

stringseven(five+6,five+10);

Thereasonisthatthenameofanobject,unlikethenameofan

array,isnottreatedastheaddressofanobject,hencefiveis

notapointerandfive+6ismeaningless.However,five[6]

isacharvalue,so&five[6]isanaddressandcanbeusedas

anargumenttotheconstructor:

stringseven(&five[6],&five[10]);//ctor#6again



stringClassInput

Anotherusefulthingtoknowaboutaclassiswhatinputoptions

areavailable.ForC-stylestrings,recall,youhavethreeoptions:



charinfo[100];

cin>>info;//readaword

cin.getline(info,100);//readaline,discard\n

cin.get(info,100);//readaline,leave\ninqueue

Sowhataretheinputoptionsforastringobject?First,the

stringclassoverloadsthe>>operator,muchastheString

classdidinChapter12.Becausethefirstoperandisnota

stringobject,theoverloaded>>operatorfunctionisnota

classmethod.Instead,itisageneralfunctiontakingan

istreamobjectasitsfirstargumentandastringobjectasits

secondargument.Tobeconsistentwithhowthe>>operator

treatsC-strings,thestringversionalsoreadsasingleword,

terminatinginputuponreachingawhitespacecharacter,

detectingendoffile,orreachingthemaximumallowable

numberofcharactersthatcanbestoredinastringobject.The

functionworksbyfirsterasingthecontentsofthetargetstring

andthenreadingandappendingonecharacteratatime.As

longastheinputsequenceisshorterthanthemaximum

allowablenumberofcharactersforastringobject,the

operator>>(istream&,string&)functionautomatically

dimensionsthestringobjecttofittheinputstring.Theupshot

isthatyoucanuse>>withstringobjectsjustasyoudowith

C-stylestrings,butwithoutworryingaboutoverrunningthe

arraysize:

charfname[10];



cin>>fname;//couldbeaproblemifinputsize>9char

stringlname;



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

Chapter 16. THE string CLASS AND THE STANDARD TEMPLATE LIBRARY

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

×