Tải bản đầy đủ - 0 (trang)
Chapter 6. Inheritance: Getting a Lot for a Little

Chapter 6. Inheritance: Getting a Lot for a Little

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

Ontheotherhand,asuccessfullylazy(andsmart)programmer

approachesanewassignmentabitdifferently.Shelooks

aroundforcodeshecanreuseorrepurpose.Shesearchesfor

codeontheInternet,inbooksandmagazines,andin

commercialcodelibraries.Asshedoes,sheusuallyfindsthat

shecanreuseorrepurposecodeforabout50%80%ofher

task.Thissavesheratremendousamountofeffortandenables

hertofinishmuchmorequicklythanthehard-working(butnot

quitesosmart)programmer.Shehasthentimetoconcentrate

hercreativityonthemostimportantpartsofthegamesothat

shecanmakeamoreinnovativeanduniquegame.

Inprogramming,reusingcode,orbeingsuccessfullylazy,isa

subjectcalledinheritance,whichwe'lldiscussinthischapter.

Themostimportantreasonforstudyingandusinginheritance

canbesummedupwiththeoldsaying,"Worksmarter,not

harder."Inheritancehelpsusdojustthat.







WhatIsInheritance?

Inobject-orientedprogramminglanguages,inheritanceisaway

ofenhancingexistingclassesoralteringtheirfunctionality

withoutrewritingthem.Imagineyou'rewritingaracinggame.

Itwouldbesensibleinthatsituationtocreateaclasscalledcar.

Thecarclasswouldcontainsuchinformationasthecar's

currentspeed,weight,horsepower,andsoforth.

Thecarclassisgeneric.Ideally,youwouldliketouseitfordrag

racers,stockcars,andsoon.Inheritanceletsyoudothat.You

canusethecarclasstocreatesuchclassesasdrag_racerand

stock_car.Thedrag_racerandstock_carclasseshaveallofthe

functionalityofthecarclass.Theyalsoaddfunctionalitythatis

specifictotheirowntypesofracecars.Forexample,dragracers

haveparachutes,butgenericandstockcarsdon't.Therefore,

thedrag_racerclasscanaddadatamemberthatspecifiesthe

dragproducedbytheparachute.Itshouldalsohaveadata

memberthatistrueiftheparachuteisdeployedandfalseifnot.

Inheritanceenablesyoutowriteagenericcarclasscontaining

thebasicfunctionalityofallcars.Youcanuseittoimplement

thedrag_racerclass,andthedrag_racerclassaddsmorefeatures.

Inaddition,youcanusethesamecarclassasthebasisfor

implementingthestock_carclass.Thissavesyoueffort.Inother

words,yougettobesuccessfullylazy.

Gameprogrammersoftendrawinheritancediagramstohelp

themfigureouttheinheritanceofalltheobjectsintheirgames.

Figure6.1showsanexampleofaninheritancediagram.



Figure6.1.Inheritanceintheracinggame.



Asthisdiagramshows,boththedrag_racerandstock_carclasses

inheritfromthecarclass.Youcantellthisbythefactthatthe

arrowspointfromdrag_racerandstock_cartocar.

Whenclassesinheritfromanotherclass,theclasstheyinherit

fromiscalledthebaseclassorparentclass.Theclassesthat

inheritfromthebaseclassarecalledthederivedclassesor

childclasses.InFigure6.1,thecarclassisthebaseorparent

classandthedrag_racerandstock_carclassesarethederivedor

childclasses.

It'simportanttonotethatwhenchildclassesderivefrom

parentclasses,thechildreninheritallofthememberdataand

functionsoftheparent.Forinstance,Figure6.1showsthatthe

drag_racerclasscontainstwoitemsofmemberdatathatboth

relatetothedragracer'sparachute.However,becausedrag_racer

inheritsfromcar,itessentiallyhasacarobjectbuiltintoit

automatically.Asaresult,drag_racerinheritsallofthemember

datayouseeincar.Figure6.2illustratesthis.



Figure6.2.Childclassesactuallycontainaparent



classobject.



Asthefigureshows,thederiveddrag_racerandstock_carobjects

containacopyofacarobject.Theembeddedcarobjectis

invisibleandunnamed.Itsfunctionsarepartofthechildobject.

Inthisway,thechildobjectsinheritallofthememberdataand

memberfunctionsoftheparent.







DerivingClasses

Ingames,it'snotuncommontodefineclassesthatrepresent

pointsin2Dspaces.Programmersalsodothesameforpoints

in3Dspaces.However,pointsin2Dspaceshavealotin

commonwithpointsin3Dspaces.Forinstance,theybothhave

xandycoordinates.Theybothneedfunctionstogetandset

thexandycoordinates.Thissuggeststhatcodefromtheclass

thatrepresentsthe2Dpointcanbereusedintheclassthat

representsthe3Dpoint.Listing6.1demonstrateshowtouse

inheritancetodefine2Dand3Dpointclasses.



Listing6.1.Derivingthepoint3dclassfromthe

point2dclass



1#include

2#include

3

4usingnamespacestd;

5

6classpoint2d

7{

8public:

9point2d();

10point2d(intxValue,intyValue);

11

12voidX(intxValue);

13intX(void);

14voidY(intyValue);

15intY(void);

16

17private:

18intx,y;

19};

20

21

22inlinepoint2d::point2d()

23{

24x=y=0;

25}

26

27



28inlinepoint2d::point2d(intxValue,intyValue)

29{

30x=xValue;

31y=yValue;

32}

33

34inlinevoidpoint2d::X(intxValue)

35{

36x=xValue;

37}

38

39inlineintpoint2d::X(void)

40{

41return(x);

42}

43

44inlinevoidpoint2d::Y(intyValue)

45{

46y=yValue;

47}

48

49inlineintpoint2d::Y(void)

50{

51return(y);

52}

53

54

55classpoint3d:publicpoint2d

56{

57public:

58point3d();

59point3d(intxValue,intyValue,intzValue);

60

61voidZ(intzValue);

62intZ(void);

63private:

64intz;

65};

66

67inlinepoint3d::point3d():point2d()

68{

69z=0;

70}

71

72

73inlinepoint3d::point3d(

74intxValue,

75intyValue,

76intzValue):point2d(xValue,yValue)

77{

78z=zValue;

79}

80

81inlinevoidpoint3d::Z(intzValue)

82{

83z=zValue;



84}

85

86inlineintpoint3d::Z(void)

87{

88return(z);

89}

90

91

92intmain(intargc,char*argv[])

93{

94point3drightHere(40,50,60);

95

96cout<<"(x,y,z)=("<
97cout<<","<
98cout<<","<
99cout<
100

101rightHere.X(10);

102rightHere.Y(20);

103rightHere.Z(30);

104

105cout<<"(x,y,z)=("<
106cout<<","<
107cout<<","<
108cout<
109

110rightHere.X(30);

111rightHere.Y(20);

112rightHere.Z(10);

113

114cout<<"(x,y,z)=("<
115cout<<","<
116cout<<","<
117cout<
118

119system("PAUSE");

120return(EXIT_SUCCESS);

121}



Listing6.1declaresaclasscalledpoint2donlines619that

representsapointina2DCartesiancoordinatesystem.Asyou

mightexpect,ithastwoconstructorsaswellasmember

functions,forsettingandgettingthexandyvaluesofthe

point.

Line55showsthedefinitionofaclasscalledpoint3d,which

representsapointina3DCartesiancoordinatesystem.Itlooks

verymuchlikethedefinitionofanyotherclass.However,the



nameofthepoint3dclassisfollowedbyacolon.Afterthecolon

isthekeywordpublic,whichisfollowedbythenamepoint2d.The

colonindicatesthatthepoint3dclassinheritsfromanotherclass.

Thekeywordpublicandthenamepoint2dspecifythatthepoint3d

classinheritsfromthepoint2dclass,asillustratedinFigure6.3.



Figure6.3.Thepoint3dclassinheritsfrom

point2d.



Lines5862showthatthepoint3dclasshastwoconstructorsand

apairoffunctionsforsettingandgettingthezcoordinateofthe

pointin3Dspace.Line64definesaprivatedatamembercalled

z.Thatistheonlymemberdatathatthepoint3dclassneeds.



Note

RecallthatC++programmersoftenreferto

parametersasarguments.Soa3-argconstructoris

aconstructorwiththreeargumentsorparameters.



Ifyouskipdowntoline94ofListing6.1,you'llseethatthe

programdeclaresapoint3dvariablecalledrightHere.Whenthe

programexecutesthisstatement,itautomaticallycallsthe3-



argconstructorforthepoint3dclass.Thecodeforthe3-arg

constructorisgivenonlines7379.Theconstructor'sthree

parameterscontainthex,y,andzvaluespassedinfromline

94.

Whenthestatementonline94declaresthepoint3dvariable,the

programautomaticallycreatesaninvisiblepoint2dvariableinside

it.Thatinvisiblepoint2dvariablemustbeinitializedwhenever

thepoint3dconstructoriscalled.That'swhythatthelast

parameteronline76isfollowedbyacolonandthenacallto

thepoint2dconstructor.AsFigure6.4shows,writingthepoint3d

constructorusingthissyntaxinvokesthe2-argpoint2d

constructorandpassesittheparametersxValueandyValue.



Figure6.4.Callingthebaseclassconstructor

fromthederivedclass.



The2-argconstructorforthepoint2dclassisonlines2832.It

setstheprivatedatamembersxandytothevaluesitreceives

throughitsparameterlist.Whenthe2-argconstructorforthe

point2dclassends,theprogramjumpsbacktothebodyofthe

3-argconstructorforthepoint3dclassbeginningonline77.

Becausetheconstructorforthepoint2dclasswascalledonline

76,youcanbeassuredthattheinvisiblepoint2dobjectisina

knownstatebeforethebodyofthepoint3dconstructorexecutes.

Theonlyremainingtaskistoinitializethememberdata

declaredinthepoint3dclass.That'sexactlywhathappenson

line78.



Programexecutionnowjumpsbacktoline94andcontinueson

line96.Atthispoint,theprogramcallstheX()functionusing

thepoint3dvariablerightHere.However,ifyoulookatthe

definitionofthepoint3dclass,you'llseethatthereisnofunction

calledX().Thatisnotaproblembecausepoint3dinheritstheX()

functionfrompoint2d.Yourprogramscancallfunctionsinbase

classesusingvariablesofderivedtypesasthisprogramdoeson

lines96and97whenitcallstheX()andY()functionsusingthe

point3dvariable.

TheprograminListing6.1demonstratesthatthepoint3dclass

inheritsallofthememberdataandfunctionsofthepoint2d

class.Afteryouwritethepoint2dclass,youdon'thavetorewrite

anyofitsfunctionalityforthepoint3dclass.Itgotthat

automaticallythroughinheritance,whichsavedyoualotof

work.



ProtectedMembers

C++hasawayforbaseclassestoprovidederivedclasseswith

accesstosomeoftheirprivatememberdataorfunctions.By

changingprivatememberdataorfunctionstoprotected,all

derivedclassescanaccessthem.Listing6.2givesanexample.



Listing6.2.Protectedmemberdata



1#include

2#include

3

4usingnamespacestd;

5

6classbase

7{

8protected:

9intanInt;

10};

11

12classderived:publicbase

13{

14public:

15voidAFunction(inttheInt);

16};

17

18inlinevoidderived::AFunction(inttheInt)

19{

20anInt=theInt;

21

22cout<
23}

24

25intmain(intargc,char*argv[])

26{

27derivedtemp;

28

29temp.AFunction(5);

30

31system("PAUSE");

32returnEXIT_SUCCESS;

33}



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

Chapter 6. Inheritance: Getting a Lot for a Little

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

×