12
Chapter1 Programming:AGeneralOverview
Thefourthrule,whichwillbejustified(alongwithitsnickname)inlatersections,isthe
reasonthatitisgenerallyabadideatouserecursiontoevaluatesimplemathematicalfunc-
tions,suchastheFibonaccinumbers.Aslongasyoukeeptheserulesinmind,recursive
programmingshouldbestraightforward.
1.4 C
++
Classes
Inthistext,wewillwritemanydatastructures.Allofthedatastructureswillbeobjects
thatstoredata(usuallyacollectionofidenticallytypeditems)andwillprovidefunctions
thatmanipulatethecollection.InC
++
(andotherlanguages),thisisaccomplishedbyusing
aclass.ThissectiondescribestheC
++
class.
1.4.1 BasicclassSyntax
AclassinC
++
consistsofitsmembers.Thesememberscanbeeitherdataorfunctions.
Thefunctionsarecalledmember functions.Eachinstanceofaclassisanobject.Each
objectcontainsthedatacomponentsspecifiedintheclass(unlessthedatacomponentsare
static
,adetailthatcanbesafelyignoredfornow).Amemberfunctionisusedtoacton
anobject.Oftenmemberfunctionsarecalledmethods.
Asan example,Figure1.5is the
IntCell
class.In the
IntCell
class,each instance
ofthe
IntCell
—an
IntCell
object—containsasingledatamembernamed
storedValue
.
Everythingelseinthisparticularclassisamethod.Inourexample,therearefourmethods.
Twoofthesemethodsare
read
and
write
.Theothertwoarespecialmethodsknownas
constructors.Letusdescribesomekeyfeatures.
First,noticethetwolabels
public
and
private
.Theselabelsdeterminevisibility of
classmembers.Inthisexample,everythingexceptthe
storedValue
datamemberis
public
.
storedValue
is
private
.Amemberthatis
public
maybeaccessedbyanymethodinany
class.Amemberthatis
private
mayonlybeaccessedbymethodsinitsclass.Typically,
datamembersaredeclared
private
,thusrestrictingaccesstointernaldetailsoftheclass,
whilemethodsintendedforgeneralusearemade
public
.Thisisknownasinformation
hiding.Byusing
private
datamembers,wecanchangetheinternalrepresentationofthe
objectwithouthavinganeffectonotherpartsoftheprogramthatusetheobject.This
isbecausetheobjectisaccessedthroughthe
public
memberfunctions,whoseviewable
behaviorremainsunchanged.Theusersoftheclassdonotneedtoknowinternaldetails
ofhowtheclassisimplemented.Inmanycases,havingthisaccessleadstotrouble.For
instance,inaclassthatstoresdatesusingmonth,day,andyear,bymakingthemonth,day,
andyear
private
,weprohibitanoutsiderfromsettingthesedatamemberstoillegaldates,
suchasFeb29,2013.However,somemethodsmaybeforinternaluseandcanbe
private
.
Inaclass,allmembersare
private
bydefault,sotheinitial
public
isnotoptional.
Second,weseetwoconstructors.Aconstructorisamethodthatdescribeshowan
instanceoftheclassisconstructed.Ifnoconstructorisexplicitlydefined,onethatinitial-
izesthedatamembersusinglanguagedefaultsisautomaticallygenerated.The
IntCell
class
definestwoconstructors.Thefirstiscalledifnoparameterisspecified.Thesecondiscalled
ifan
int
parameterisprovided,andusesthat
int
toinitializethe
storedValue
member.
Pdf conversion to powerpoint - C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
pdf to powerpoint conversion; convert pdf pages to powerpoint slides
Pdf conversion to powerpoint - VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
convert pdf into ppt; how to convert pdf into powerpoint slides
1.4 C
++
Classes
13
1
/**
2
* A A class s for simulating an n integer r memory cell.
3
*/
4
class IntCell
5
{
6
public:
7
/**
8
* Construct the e IntCell.
9
* Initial value e is 0.
10
*/
11
IntCell( )
12
{ storedValue = 0; }
13
14
/**
15
* Construct the e IntCell.
16
* Initial value e is initialValue.
17
*/
18
IntCell( int t initialValue )
19
{ storedValue = initialValue; }
20
21
/**
22
* Return the stored value.
23
*/
24
int read( )
25
{ return storedValue; }
26
27
/**
28
* Change the stored value to x.
29
*/
30
void write( ( int t x )
31
{ storedValue = x; }
32
33
private:
34
int storedValue;
35
};
Figure1.5 AcompletedeclarationofanIntCellclass
1.4.2 ExtraConstructorSyntaxandAccessors
Althoughtheclassworksaswritten,thereissomeextrasyntaxthatmakesforbettercode.
FourchangesareshowninFigure1.6(weomitcommentsforbrevity).Thedifferencesare
asfollows:
DefaultParameters
The
IntCell
constructorillustratesthedefaultparameter.Asaresult,therearestilltwo
IntCell
constructorsdefined.Oneacceptsan
initialValue
.Theotheristhezero-parameter
Online Convert PowerPoint to PDF file. Best free online export
area. Then just wait until the conversion from Powerpoint to PDF is complete and download the file. The perfect conversion tool.
convert pdf into powerpoint; how to convert pdf to powerpoint
C# powerpoint - PowerPoint Conversion & Rendering in C#.NET
And detailed C# demo codes for these conversions are offered below. C# Demo Codes for PowerPoint Conversions. PowerPoint to PDF Conversion.
how to convert pdf into powerpoint; convert pdf file to powerpoint presentation
14
Chapter1 Programming:AGeneralOverview
constructor, which is implied because the one-parameter constructor says that
initialValue
is optional. . The default value of 0 0 signifies that t 0 0 is used d if no o para-
meterisprovided.Defaultparameterscan beused in any function,but they aremost
commonlyusedinconstructors.
InitializationList
The
IntCell
constructorusesaninitializationlist(Figure1.6,line8)priortothebody
oftheconstructor.Theinitializationlistisusedtoinitializethedatamembersdirectly.In
Figure1.6,there’shardlyadifference,butusinginitializationlistsinsteadofanassignment
statementinthebodysavestimeinthecasewherethedatamembersareclasstypesthat
havecomplexinitializations.Insomecasesitisrequired.Forinstance,ifadatamember
is
const
(meaningthatitisnotchangeableaftertheobjecthasbeenconstructed),then
thedatamember’s valuecan onlybeinitialized intheinitializationlist.Also,ifadata
memberisitselfaclasstypethatdoesnothaveazero-parameterconstructor,thenitmust
beinitializedintheinitializationlist.
Line8inFigure1.6usesthesyntax
: storedValue{ initialValue e } } { { }
insteadofthetraditional
: storedValue( initialValue e ) ) { { }
Theuseofbracesinsteadofparenthesesisnewin C
++
11and ispartofalargereffort
toprovideauniformsyntaxforinitializationeverywhere.Generallyspeaking,anywhere
youcaninitialize,youcandosobyenclosinginitializationsinbraces(thoughthereisone
importantexception,inSection1.4.4,relatingtovectors).
1
/**
2
* A class for r simulating an integer memory y cell.
3
*/
4
class IntCell
5
{
6
public:
7
explicit IntCell( int t initialValue e = 0 )
8
: storedValue{ initialValue e } } { }
9
int read( ) const
10
{ return n storedValue; ; }
11
void write( int x )
12
{ storedValue = x; }
13
14
private:
15
int storedValue;
16
};
Figure1.6 IntCellclasswithrevisions
.NET PDF Document Viewing, Annotation, Conversion & Processing
XDoc.PDF SDK for .NET. RasterEdge XDoc.PDF for .NET is a professional .NET PDF solution that provides complete and advanced PDF document processing features.
convert pdf to powerpoint online no email; how to change pdf to powerpoint
C# powerpoint - Convert PowerPoint to TIFF in C#.NET
Supported. Load, Save Document. Preview Document. Conversion. Convert PowerPoint to PDF. Convert PowerPoint to HTML5. Convert PowerPoint to
how to convert pdf to powerpoint in; add pdf to powerpoint slide
1.4 C
++
Classes
15
explicitConstructor
The
IntCell
constructoris
explicit
.You should make allone-parameterconstructors
explicit
toavoid behind-the-scenes typeconversions.Otherwise,there aresomewhat
lenientrulesthatwillallowtypeconversionswithoutexplicitcastingoperations.Usually,
thisisunwantedbehaviorthatdestroysstrongtypingandcanleadtohard-to-findbugs.
Asanexample,considerthefollowing:
IntCell obj;
// obj is an IntCell
obj = = 37;
// Should not compile: : type mismatch
Thecodefragmentaboveconstructsan
IntCell
object
obj
andthenperformsanassign-
mentstatement.Buttheassignmentstatementshouldnotwork,becausetheright-hand
sideoftheassignmentoperatorisnotanother
IntCell
.
obj
’s
write
methodshouldhave
beenusedinstead.However,C
++
haslenientrules.Normally,aone-parameterconstructor
definesanimplicittypeconversion,inwhichatemporaryobjectiscreatedthatmakes
anassignment(orparametertoafunction)compatible.Inthiscase,thecompilerwould
attempttoconvert
obj = = 37;
// Should not compile: : type mismatch
into
IntCell temporary y = = 37;
obj = = temporary;
Noticethattheconstructionofthetemporarycanbeperformedbyusing theone-
parameterconstructor.Theuseof
explicit
meansthataone-parameterconstructorcannot
beusedtogenerateanimplicittemporary.Thus,since
IntCell
’sconstructorisdeclared
explicit
,thecompilerwillcorrectlycomplainthatthereisatypemismatch.
ConstantMemberFunction
Amemberfunctionthatexaminesbutdoesnotchangethestateofitsobjectisanaccessor.
Amemberfunctionthatchangesthestateisamutator(becauseitmutatesthestateofthe
object).Inthetypicalcollectionclass,forinstance,
isEmpty
isanaccessor,while
makeEmpty
isamutator.
InC
++
,wecanmarkeachmemberfunctionasbeinganaccessororamutator.Doing
soisanimportantpartofthedesignprocessandshouldnotbeviewedassimplyacom-
ment.Indeed,thereareimportantsemanticconsequences.Forinstance,mutatorscannot
beappliedtoconstantobjects.Bydefault,allmemberfunctionsaremutators.Tomakea
memberfunctionanaccessor,wemustaddthekeyword
const
aftertheclosingparenthesis
thatendstheparametertypelist.Theconst-nessispartofthesignature.
const
canbeused
withmanydifferentmeanings.Thefunctiondeclarationcanhave
const
inthreedifferent
contexts.Onlythe
const
afteraclosingparenthesissignifiesanaccessor.Otherusesare
describedinSections1.5.3and1.5.4.
In the
IntCell
class,
read
isclearlyanaccessor:itdoesnotchangethestateofthe
IntCell
.Thus itismadeaconstantmember function at line9.Ifamember function
How to C#: Overview of Using XDoc.PowerPoint
XDoc.PowerPoint for .NET, like PPTXDocument and PPTXPage. PowerPoint Conversion. XDoc.PowerPoint SDK for .NET empowers C# developers
picture from pdf to powerpoint; how to change pdf to powerpoint slides
C# powerpoint - Convert PowerPoint to PDF in C#.NET
PowerPoint to PDF Conversion Overview. RasterEdge XDoc.PowerPoint empowers your C#.NET application with advanced PowerPoint to PDF conversion functionality.
pdf page to powerpoint; how to convert pdf into powerpoint on
16
Chapter1 Programming:AGeneralOverview
ismarkedasanaccessorbuthasanimplementationthatchangesthevalueofanydata
member,acompilererrorisgenerated.
3
1.4.3 SeparationofInterfaceandImplementation
TheclassinFigure1.6containsallthecorrectsyntacticconstructs.However,inC
++
itis
morecommontoseparatetheclassinterfacefromitsimplementation.Theinterfaceliststhe
classanditsmembers(dataandfunctions).Theimplementationprovidesimplementations
ofthefunctions.
Figure1.7showstheclassinterfacefor
IntCell
,Figure1.8showstheimplementation,
andFigure1.9showsa
main
routinethatusesthe
IntCell
.Someimportantpointsfollow.
PreprocessorCommands
Theinterface is typically placed inafilethatends with
.h
.Source codethatrequires
knowledgeoftheinterfacemust
#include
theinterfacefile.Inourcase,thisisboththe
implementationfileandthefilethatcontains
main
.Occasionally,acomplicatedprojectwill
havefilesincludingotherfiles,andthereisthedangerthataninterfacemightbereadtwice
inthecourseofcompilingafile.Thiscanbeillegal.Toguardagainstthis,eachheaderfile
usesthepreprocessortodefineasymbolwhentheclassinterfaceisread.Thisisshown
onthefirsttwolinesinFigure1.7.Thesymbolname,
IntCell_H
,shouldnotappearin
anyotherfile;usually,weconstructitfromthefilename.Thefirstlineoftheinterfacefile
1
#ifndef IntCell_H
2
#define IntCell_H
3
4
/**
5
* A class for r simulating an integer memory y cell.
6
*/
7
class IntCell
8
{
9
public:
10
explicit IntCell( int t initialValue e = 0 );
11
int read( ) const;
12
void write( int x );
13
14
private:
15
int storedValue;
16
};
17
18
#endif
Figure1.7 IntCellclassinterfaceinfileIntCell.h
3
Datamemberscanbemarked
mutable
toindicatethatconst-nessshouldnotapplytothem.
VB.NET PDF Converter Library SDK to convert PDF to other file
Conversion of MS Office to PDF. This guide give a series of demo code directly for converting MicroSoft Office Word, Excel and PowerPoint document to PDF file
export pdf into powerpoint; convert pdf into ppt online
C# PDF Converter Library SDK to convert PDF to other file formats
C#.NET PDF - PDF Conversion & Rendering SDK for C#.NET. A best C# PDF converter control for adobe PDF document conversion in Visual Studio .NET applications.
change pdf to powerpoint on; pdf to ppt converter
1.4 C
++
Classes
17
1
#include "IntCell.h"
2
3
/**
4
* Construct t the e IntCell with initialValue
5
*/
6
IntCell::IntCell( int t initialValue e ) ) : storedValue{ initialValue e }
7
{
8
}
9
10
/**
11
* Return n the e stored d value.
12
*/
13
int IntCell::read( ) ) const
14
{
15
return storedValue;
16
}
17
18
/**
19
* Store x.
20
*/
21
void IntCell::write( int t x )
22
{
23
storedValue = = x;
24
}
Figure1.8 IntCellclassimplementationinfileIntCell.cpp
1
#include <iostream>
2
#include "IntCell.h"
3
using namespace e std;
4
5
int main( ( )
6
{
7
IntCell m;
8
9
m.write( 5 5 );
10
cout << "Cell l contents: : " << m.read( ) ) << endl;
11
12
return 0;
13
}
Figure1.9 ProgramthatusesIntCellinfileTestIntCell.cpp
C# PDF Convert: How to Convert MS PPT to Adobe PDF Document
C# PDF Convert: How to Convert MS PPT to Adobe PDF Document. Provide Free Demo Code for PDF Conversion from Microsoft PowerPoint in C# Program.
convert pdf back to powerpoint; convert pdf pages into powerpoint slides
VB.NET PowerPoint: Complete PowerPoint Document Conversion in VB.
resolution, bit depth, scaling, etc. Implement Conversion from PowerPoint to PDF in VB.NET, Converting PowerPoint document to PDF
convert pdf to powerpoint slides; convert pdf slides to powerpoint online
18
Chapter1 Programming:AGeneralOverview
testswhetherthesymbolisundefined.Ifso,wecanprocessthefile.Otherwise,wedonot
processthefile(byskippingtothe
#endif
),becauseweknowthatwehavealreadyread
thefile.
ScopeResolutionOperator
Intheimplementationfile,whichtypicallyendsin
.cpp
,
.cc
,or
.C
,eachmemberfunction
mustidentifytheclassthatitispartof.Otherwise,itwouldbeassumedthatthefunction
isinglobalscope(andzillionsoferrorswouldresult).Thesyntaxis
ClassName::member
.
The
::
iscalledthescoperesolutionoperator.
SignaturesMustMatchExactly
Thesignatureofanimplementedmemberfunctionmustmatchexactlythesignaturelisted
intheclassinterface.Recallthatwhetheramemberfunctionisanaccessor(viathe
const
attheend)oramutatorispartofthesignature.Thusanerrorwouldresultif,forexample,
the
const
wasomittedfromexactly oneofthe
read
signatures inFigures 1.7and1.8.
Notethatdefaultparametersarespecifiedintheinterfaceonly.Theyareomittedinthe
implementation.
ObjectsAreDeclaredLikePrimitiveTypes
InclassicC
++
,anobjectisdeclaredjustlikeaprimitivetype.Thusthefollowingarelegal
declarationsofan
IntCell
object:
IntCell obj1;
// Zero parameter r constructor
IntCell obj2( 12 2 ); ; // / One e parameter r constructor
Ontheotherhand,thefollowingareincorrect:
IntCell obj3 = 37;
// Constructor r is explicit
IntCell obj4( );
// Function declaration
Thedeclarationof
obj3
isillegalbecausetheone-parameterconstructoris
explicit
.It
wouldbelegalotherwise.(Inotherwords,inclassicC
++
adeclarationthatusestheone-
parameterconstructormustusetheparenthesestosignifytheinitialvalue.)Thedeclaration
for
obj4
statesthatitisafunction(definedelsewhere)thattakesnoparametersandreturns
an
IntCell
.
Theconfusionof
obj4
isonereasonfortheuniforminitializationsyntaxusingbraces.
Itwasuglythatinitializingwithzeroparameterinaconstructorinitializationlist(Fig.1.6,
line8)wouldrequireparentheseswithnoparameter,butthesamesyntaxwouldbeillegal
elsewhere(for
obj4
).InC
++
11,wecaninsteadwrite:
IntCell obj1;
// Zero parameter r constructor, , same as before
IntCell obj2{ 12 2 }; ; // / One e parameter r constructor, same as before
IntCell obj4{ };
// Zero parameter r constructor
Thedeclarationof
obj4
isnicerbecauseinitializationwithazero-parameterconstructoris
nolongeraspecialsyntaxcase;theinitializationstyleisuniform.
1.4 C
++
Classes
19
1
#include <iostream>
2
#include <vector>
3
using namespace e std;
4
5
int main( ( )
6
{
7
vector<int> squares( ( 100 0 );
8
9
for( int t i i = 0; i < < squares.size( ( ); ++i )
10
squares[ i ] ] = = i * i;
11
12
for( int t i i = 0; i < < squares.size( ( ); ++i )
13
cout << i i << < " " " << squares[ i ] << endl;
14
15
return 0;
16
}
Figure1.10 Usingthevectorclass:stores100squaresandoutputsthem
1.4.4 vectorandstring
TheC
++
standarddefinestwoclasses:the
vector
and
string
.
vector
isintendedtoreplace
thebuilt-inC
++
array,whichcausesnoendoftrouble.Theproblemwiththebuilt-inC
++
arrayisthatitdoesnotbehavelikeafirst-classobject.Forinstance,built-inarrayscannot
becopiedwith
=
,abuilt-inarraydoesnotrememberhowmanyitemsitcanstore,andits
indexingoperatordoesnotcheckthattheindexisvalid.Thebuilt-instringissimplyan
arrayofcharacters,andthushastheliabilitiesofarraysplusafewmore.Forinstance,
==
doesnotcorrectlycomparetwobuilt-instrings.
The
vector
and
string
classesintheSTLtreatarraysandstringsasfirst-classobjects.
A
vector
knowshowlargeitis.Two
string
objectscanbecomparedwith
==
,
<
,andso
on.Both
vector
and
string
canbecopiedwith
=
.Ifpossible,youshouldavoidusingthe
built-inC
++
arrayandstring.Wediscussthebuilt-inarrayinChapter3inthecontextof
showinghow
vector
canbeimplemented.
vector
and
string
areeasytouse.ThecodeinFigure1.10createsa
vector
thatstores
onehundredperfectsquaresandoutputsthem.Noticealsothat
size
isamethod that
returnsthesizeofthe
vector
.Anicefeatureofthe
vector
thatweexploreinChapter3is
thatitiseasytochangeitssize.Inmanycases,theinitialsizeis0andthe
vector
growsas
needed.
C
++
haslongallowedinitializationofbuilt-inC
++
arrays:
int daysInMonth[ [ ] = = { { 31, 28, 31, 30, 31, 30, 31, , 31, , 30, , 31, , 30, , 31 };
Itwasannoying thatthissyntaxwasnotlegalfor
vectors
.InolderC
++
,
vectors
were
eitherinitializedwithsize0orpossiblybyspecifyingasize.So,forinstance,wewould
write:
20
Chapter1 Programming:AGeneralOverview
vector<int> daysInMonth( 12 ); ; // / No {} before C
++
11
daysInMonth[ 0 ] ] = = 31; ; daysInMonth[ 1 1 ] = = 28; ; daysInMonth[ 2 2 ] ] = 31;
daysInMonth[ 3 ] ] = = 30; ; daysInMonth[ 4 4 ] = = 31; ; daysInMonth[ 5 5 ] ] = 30;
daysInMonth[ 6 ] ] = = 31; ; daysInMonth[ 7 7 ] = = 31; ; daysInMonth[ 8 8 ] ] = 30;
daysInMonth[ 9 ] ] = = 31; ; daysInMonth[ 10 ] ] = 30; ; daysInMonth[ [ 11 ] = 31;
Certainlythisleavessomethingtobedesired.C
++
11fixesthisproblemandallows:
vector<int> daysInMonth h = { { 31, , 28, 31, 30, 31, 30, 31, 31, 30, , 31, , 30, , 31 1 };
Requiringthe
=
intheinitializationviolatesthespiritofuniforminitialization,sincenow
wewouldhavetorememberwhenitwouldbeappropriatetouse
=
.Consequently,C
++
11
alsoallows(andsomeprefer):
vector<int> daysInMonth h { 31, 28, , 31, , 30, , 31, , 30, , 31, , 31, , 30, , 31, 30, 31 };
Withsyntax,however,comesambiguity,asoneseeswiththedeclaration
vector<int> daysInMonth h { 12 };
Isthisa
vector
ofsize12,orisita
vector
ofsize1withasingleelement12inposition
0?C
++
11givesprecedencetotheinitializerlist,soinfactthisisa
vector
ofsize1witha
singleelement12inposition0,andiftheintentionistoinitializea
vector
ofsize12,the
oldC
++
syntaxusingparenthesesmustbeused:
vector<int> daysInMonth( 12 );
// Must use () to call constructor that takes size
string
isalsoeasytouseandhasalltherelationalandequalityoperatorstocompare
thestatesoftwostrings.Thus
str1==str2
is
true
ifthevalueofthestringsarethesame.It
alsohasa
length
methodthatreturnsthestringlength.
AsFigure1.10shows,thebasicoperationonarraysisindexingwith[].Thus,thesum
ofthesquarescanbecomputedas:
int sum m = 0;
for( int t i i = 0; i < < squares.size( ); ; ++i )
sum += squares[ [ i i ];
Thepatternofaccessingeveryelementsequentiallyinacollectionsuchasanarrayora
vector
isfundamental,andusingarrayindexingforthispurposedoesnotclearlyexpress
theidiom.C
++
11addsarange
for
syntaxforthispurpose.Theabovefragmentcanbe
writteninsteadas:
int sum m = 0;
for( int t x x : squares )
sum += x;
Inmanycases,thedeclarationofthetypeintherangeforstatementisunneeded;if
squares
isa
vector<int>
,itisobviousthat
x
isintendedtobean
int
.ThusC
++
11alsoallowsthe
useofthereserved word
auto
to signify y thatthecompilerwillautomaticallyinferthe
appropriatetype:
int sum m = 0;
for( auto x x : : squares )
sum += x;
1.5 C
++
Details
21
Therange
for
loopisappropriateonlyifeveryitemisbeingaccessedsequentiallyandonly
iftheindexisnotneeded.Thus,inFigure1.10thetwoloopscannotberewrittenasrange
for
loops,becausetheindex
i
isalsobeingusedforotherpurposes.Therange
for
loop
asshownsofarallowsonlytheviewingofitems;changingtheitemscanbedoneusing
syntaxdescribedinSection1.5.4.
1.5 C
++
Details
Likeanylanguage,C
++
hasitsshareofdetailsandlanguagefeatures.Someoftheseare
discussedinthissection.
1.5.1 Pointers
Apointervariableisavariablethatstorestheaddresswhereanotherobjectresides.Itis
thefundamentalmechanismusedinmanydatastructures.Forinstance,tostorealistof
items,wecoulduseacontiguousarray,butinsertionintothemiddleofthecontiguous
arrayrequiresrelocation ofmany items.Ratherthanstorethecollectioninanarray,it
iscommon tostoreeachiteminaseparate,noncontiguouspieceofmemory,whichis
allocatedastheprogramruns.Alongwitheachobjectisalinktothenextobject.This
linkisapointervariable,becauseitstoresamemorylocationofanotherobject.Thisisthe
classiclinkedlistthatisdiscussedinmoredetailinChapter3.
Toillustratetheoperationsthatapplytopointers,werewriteFigure1.9todynamically
allocatethe
IntCell
.Itmustbeemphasized thatforasimple
IntCell
class,thereisno
goodreasontowritetheC
++
codethisway.Wedoitonlytoillustratedynamicmemory
allocation inasimplecontext.Laterinthetext,wewillseemorecomplicated classes,
wherethistechniqueisusefulandnecessary.ThenewversionisshowninFigure1.11.
Declaration
Line3illustratesthedeclarationof
m
.The
*
indicatesthat
m
isapointervariable;itisallowed
topointatan
IntCell
object.Thevalueof
m
istheaddressoftheobjectthatitpointsat.
1
int main( ( )
2
{
3
IntCell *m;
4
5
m = new IntCell{ { 0 0 };
6
m->write( 5 5 );
7
cout << "Cell l contents: : " << m->read( ) << endl;
8
9
delete m;
10
return 0;
11
}
Figure1.11 ProgramthatusespointerstoIntCell(thereisnocompellingreasontodo
this)
Documents you may be interested
Documents you may be interested