面向对象程序设计英文Word文档下载推荐.docx

上传人:b****8 文档编号:22681876 上传时间:2023-02-05 格式:DOCX 页数:15 大小:23.08KB
下载 相关 举报
面向对象程序设计英文Word文档下载推荐.docx_第1页
第1页 / 共15页
面向对象程序设计英文Word文档下载推荐.docx_第2页
第2页 / 共15页
面向对象程序设计英文Word文档下载推荐.docx_第3页
第3页 / 共15页
面向对象程序设计英文Word文档下载推荐.docx_第4页
第4页 / 共15页
面向对象程序设计英文Word文档下载推荐.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

面向对象程序设计英文Word文档下载推荐.docx

《面向对象程序设计英文Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《面向对象程序设计英文Word文档下载推荐.docx(15页珍藏版)》请在冰豆网上搜索。

面向对象程序设计英文Word文档下载推荐.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 医学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1