面向对象程序设计英文Word文档下载推荐.docx
《面向对象程序设计英文Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《面向对象程序设计英文Word文档下载推荐.docx(15页珍藏版)》请在冰豆网上搜索。
AnOverview
ThekeyideabehindOOPispolymorphism.PolymorphismisderivedfromaGreekwordmeaning"
manyforms."
Wespeakoftypesrelatedbyinheritanceaspolymorphictypes,becauseinmanycaseswecanusethe"
manyforms"
ofaderivedorbasetypeinterchangeably.Aswe'
llsee,inC++,polymorphismappliesonlytoreferencesorpointerstotypesrelatedbyinheritance.
Inheritance
Inheritanceletsusdefineclassesthatmodelrelationshipsamongtypes,sharingwhatiscommonandspecializingonlythatwhichisinherentlydifferent.Membersdefinedbythebaseclassareinheritedbyitsderivedclasses.Thederivedclasscanuse,withoutchange,thoseoperationsthatdonotdependonthespecificsofthederivedtype.Itcanredefinethosememberfunctionsthatdodependonitstype,specializingthefunctiontotakeintoaccountthepeculiaritiesofthederivedtype.Finally,aderivedclassmaydefineadditionalmembersbeyondthoseitinheritsfromitsbaseclass.
Classesrelatedbyinheritanceareoftendescribedasforminganinheritancehierarchy.Thereisoneclass,referredtoastheroot,fromwhichalltheotherclassesinherit,directlyorindirectly.Inourbookstoreexample,wewilldefineabaseclass,whichwe'
llnameItem_base,torepresentundiscountedbooks.FromItem_basewewillinheritasecondclass,whichwe'
llnameBulk_item,torepresentbookssoldwithaquantitydiscount.
Ataminimum,theseclasseswilldefinethefollowingoperations:
●anoperationnamedbookthatwillreturntheISBN
●anoperationnamednet_pricethatreturnsthepriceforpurchasingaspecifiednumberofcopiesofabook
ClassesderivedfromItem_basewillinheritthebookfunctionwithoutchange:
ThederivedclasseshavenoneedtoredefinewhatitmeanstofetchtheISBN.Ontheotherhand,eachderivedclasswillneedtodefineitsownversionofthenet_pricefunctiontoimplementanappropriatediscountpricingstrategy.
InC++,abaseclassmustindicatewhichofitsfunctionsitintendsforitsderivedclassestoredefine.Functionsdefinedasvirtualareonesthatthebaseexpectsitsderivedclassestoredefine.Functionsthatthebaseclassintendsitschildrentoinheritarenotdefinedasvirtual.
Giventhisdiscussion,wecanseethatourclasseswilldefinethree(const)memberfunctions:
∙Anonvirtualfunction,std:
:
stringbook(),thatreturnstheISBN.ItwillbedefinedbyItem_baseandinheritedbyBulk_item.
∙Twoversionsofthevirtualfunction,doublenet_price(size_t),toreturnthetotalpriceforagivennumberofcopiesofaspecificbook.BothItem_baseandBulk_itemwilldefinetheirownversionsofthisfunction.
DynamicBinding
Dynamicbindingletsuswriteprogramsthatuseobjectsofanytypeinaninheritancehierarchywithoutcaringabouttheobjects'
specifictypes.Programsthatusetheseclassesneednotdistinguishbetweenfunctionsdefinedinthebaseorinaderivedclass.
Forexample,ourbookstoreapplicationwouldletacustomerselectseveralbooksinasinglesale.Whenthecustomerwasdoneshopping,theapplicationwouldcalculatethetotaldue.Onepartoffiguringthefinalbillwouldbetoprintforeachbookpurchasedalinereportingthetotalquantityandsalespriceforthatportionofthepurchase.
Wemightdefineafunctionnamedprint_totaltomanagethispartoftheapplication.Theprint_totalfunction,givenanitemandacount,shouldprinttheISBNandthetotalpriceforpurchasingthegivennumberofcopiesofthatparticularbook.Theoutputofthisfunctionshouldlooklike:
ISBN:
0-201-54848-8numbersold:
3totalprice:
98
0-201-82470-1numbersold:
5totalprice:
202.5
Ourprint_totalfunctionmightlooksomethinglikethefollowing:
//calculateandprintpriceforgivennumberofcopies,applyinganydiscounts
voidprint_total(ostream&
os,
constItem_base&
item,size_tn)
{
os<
<
"
ISBN:
<
item.book()//callsItem_base:
book
\tnumbersold:
n<
\ttotalprice:
//virtualcall:
whichversionofnet_pricetocallisresolvedatruntime
_price(n)<
endl;
}
Thefunction'
sworkistrivial:
Itprintstheresultsofcallingbookandnet_priceonitsitemparameter.Therearetwointerestingthingsaboutthisfunction.
First,eventhoughitssecondparameterisareferencetoItem_base,wecanpasseitheranItem_baseobjectoraBulk_itemobjecttothisfunction.
Second,becausetheparameterisareferenceandthenet_pricefunctionisvirtual,thecalltonet_pricewillberesolvedatruntime.Theversionofnet_pricethatiscalledwilldependonthetypeoftheargumentpassedtoprint_total.Whentheargumenttoprint_totalisaBulk_item,theversionofnet_pricethatisrunwillbetheonedefinedinBulk_itemthatappliesadiscount.IftheargumentisanItem_baseobject,thenthecallwillbetotheversiondefinedbyItem_base.
C++,dynamicbindinghappenswhenavirtualfunctioniscalledthroughareference(orapointer)toabaseclass.Thefactthatareference(orpointer)mightrefertoeitherabase-oraderived-classobjectisthekeytodynamicbinding.Callstovirtualfunctionsmadethroughareference(orpointer)areresolvedatruntime:
Thefunctionthatiscalledistheonedefinedbytheactualtypeoftheobjecttowhichthereference(orpointer)refers.
DefiningBaseandDerivedClasses
Inmanyways,baseandderivedclassesaredefinedlikeotherclasseswehavealreadyseen.However,therearesomeadditionalfeaturesthatarerequiredwhendefiningclassesinaninheritancehierarchy.Thissectionwillpresentthosefeatures.Subsequentsectionswillseehowuseofthesefeaturesimpactsclassesandtheprogramswewriteusinginheritedclasses.
DefiningaBaseClass
Likeanyotherclass,abaseclasshasdataandfunctionmembersthatdefineitsinterfaceandimplementation.Inthecaseofour(verysimplified)bookstorepricingapplication,ourItem_baseclassdefinesthebookandnet_pricefunctionsandneedstostoreanISBNandthestandardpriceforthebook:
//Itemsoldatanundiscountedprice
//derivedclasseswilldefinevariousdiscountstrategies
classItem_base{
public:
Item_base(conststd:
string&
book="
"
doublesales_price=0.0):
isbn(book),price(sales_price){}
std:
stringbook()const{returnisbn;
//returnstotalsalespriceforaspecifiednumberofitems
//derivedclasseswilloverrideandapplydifferentdiscountalgorithms
virtualdoublenet_price(std:
size_tn)const
{returnn*price;
virtual~Item_base(){}
private:
stringisbn;
//identifierfortheitem
protected:
doubleprice;
//normal,undiscountedprice
};
Forthemostpart,thisclasslookslikeotherswehaveseen.Itdefinesaconstructoralongwiththefunctionswehavealreadydescribed.Thatconstructorusesdefaultarguments(Section7.4.1,p.253),whichallowsittobecalledwithzero,one,ortwoarguments.Itinitializesthedatamembersfromthesearguments.
Thenewpartsaretheprotectedaccesslabelandtheuseofthevirtualkeywordonthedestructorandthenet_pricefunction.We'
llexplainvirtualdestructorsinSection15.4.4(p.587),butfornowitisworthnotingthatclassesusedastherootclassofaninheritancehierarchygenerallydefineavirtualdestructor.
Base-ClassMemberFunctions
TheItem_baseclassdefinestwofunctions,oneofwhichisprecededbythekeywordvirtual.Thepurposeofthevirtualkeywordistoenabledynamicbinding.Bydefault,memberfunctionsarenonvirtual.Callstononvirtualfunctionsareresolvedatcompiletime.Tospecifythatafunctionisvirtual,weprecedeitsreturntypebythekeywordvirtual.Anynonstaticmemberfunction,otherthanaconstructor,maybevirtual.Thevirtualkeywordappearsonlyonthemember-functiondeclarationinsidetheclass.Thevirtualkeywordmaynotbeusedonafunctiondefinitionthatappearsoutsidetheclassbody.
AccessControlandInheritance
Inabaseclass,thepublicand