oriented

更新时间:2022-11-24 01:43:51 阅读: 评论:0


2022年11月24日发(作者:出纳的职责)

面向对象编程(object-orientedprogramming)

Therearemanyobject-orientedprogramminglanguages,suchas

Smalltalk,Ada,Eiffel,Object,Pascal,Visual,Basic,C++,and

soon.C++isthemostinterestinglanguagebecauitis

compatiblewiththeClanguageandhasthecapabilityofC

ntyears,apureobject-orientedlanguage

calledJavasmashhit,manypeoplewereshoutingwithJava

leatherC++'JavaisC++'snephew,althoughnot

directlyinherited,enephew

sprinkledhisurineonhisuncle'splay,theyshouldnotquarrel

overit.

C++programmingonthebooksverymuch,thischapterdoesnot

speakC++grammar,

Ihadknownthelittletruthsinafewyears,theywouldhave

improvedthequalityofhundredsofthousandsoflines.

6.1,C++,animportantconceptinobject-orientedprogramming,

hassucharoleinearlyrevolutionaryfilms."I'mtheparty

reprentative,Ireprenttheparty,andI'mtheparty,"he

says."Later,hebroughtdisastertohiscomrades.

DoprogrammerswhouC++mustknowobjectoriented

programming?

ProgrammerswhodonotuC++mustnotunderstandobject

orientedprogramming?

Neitheristrue.

Iamnotafraidofoffendingawords:"C++notonlymasterC

languagemaster."AfterusingCandC++programmingfor8years,

IdeeplyregretisnottheClanguagemaster,morepeoplecame

nyC++

programmers,IthinkI'vegotanideaofobject-oriented

programmingwhenI'menjoyingthebenefitsofC++

toothpastetoothpastetubesthatsoldout,itisBoTimTinMat.

Peopledon'tunderstandPinyin,theycanspeakMandarin,and

iftheyknowPinyin,

orientedprogrammingcanalsobeprogrammedinC++,andifyou

knowobjectorientedprogramming,youcanmakeC++programs

ctioncoversthreeverybasicconcepts:class

andobject,inheritanceandcomposition,virtualfunctions,

andpolymorphism".Understandingtheconceptshelpsto

improvethequalityoftheprogram,especiallyintermsof

"reusability"and"scalability"".

6.1.1classandobjects

Anobject(Object)isaninstanceofaclass(Class)(Instance).

Iftheobjectiscomparedtothehou,thentheclassisthe

ointofobjectoriented

programmingisthedesignoftheclass,notthedesignofthe

canencapsulatedataandfunctions,where

functionsreprentthebehavioroftheclass(orrvice).The

classprovideskeywordspublic,protected,andprivateto

declarewhichdataandfunctionsarepublic,protected,or

private.

Thisallowsforthepurpoofinformationhiding,thatis,to

lettheclasssimplyexpowhatmustbeknowntotheoutside

world,'tabuclass

encapsulation,don'ttakeitasahotpotandthroweverything

intoit.

Isthedesignofaclasscenteredondataorbehavior?

The"datacentric"onewhopaysattentiontotheinternaldata

structureoftheclassisudtowriteprivatetypedatain

thefront,andwritesthepublictypefunctionback,asshown

intable8.1(a).

Advocate"toactasthecenter"thatntconcernedshould

providervicesandwhattheyareudtointerface,function

oftypepublicwillwriteinfront,andtheprivatedatatype

iswrittenontheback,asshownintable8.1(B).

ManyC++instructionalbooksadvocate"datacentric"inthe

designclass".Iinsistandsuggestthatthereaderbe

"behavioralcentered"whendesigningclass,firstofall,to

eof

Microsoft'sCOMspecificationistheinterfacedesign,where

theCOMinterfaceiquivalenttotheclass'spublicfunction

[Rogerson1999].Inprogramming,let'snotdoubtthestyleof

Microsoft.

It'asiertodesignisolatedclass,butit'shardtodesign

thebaclassanditsderivedclasscorrectly.

Becausomeprogrammersdon'tknowtheconceptsof

"Inheritance","Composition","Polymorphism",and

"polymorphism".

6.1.2inheritanceandcomposition

IfAisthebaclassandBisthederivedclassofA,then

pleprogramis

asfollows:

ClassA

{

Public:

VoidFunc1(void);

VoidFunc2(void);

};

ClassB:publicA

{

Public:

VoidFunc3(void);

VoidFunc4(void);

};

//Example

(main)

{

BB;//anobjectB

(1);//BinheritsfromAFunc1function

(2);//BinheritsfromAFunc2function

3();

4();

}

Thissimplesampleprogramillustratesthefactthatthe

inheritancefeatureofC++canimprovethereusabilityof

e"inheritance"istooufulandeasytou,

itisnecessarytopreventtheindiscriminateuof

"inheritance"".Weneedtotsomerulesforinheritance:

First,ifclassAandclassBareirrelevant,youcan'tletB

inheritthefunctionalityofAinordertomakeBmore

functional.

Donotthinkthatthe"freetoeatdonoteat",makeagood

athleticyouthtoeatginngtonicbodyItiswithoutrhyme

orreason.

Two,iftheclassBisnecessarytouthefunctionofA,it

shouldbeconsideredintwocas:

(1)iflogicallyBisa"A"ofA(akindof),thenBisallowed

toinheritthefunctionofa..Boyisakindofman,suchas

Human(Man).ClassMancanthenbederivedfromclassHuman,

pleprogram

isasfollows:

ClassHuman

{

...

};

ClassMan:publicHuman

{

...

};

ClassBoy:publicMan

{

...

};

(2)iflogicallyAisapartofB(apartof),Bisnotallowed

toinheritthefunctionofA,butBistobecombinedwithA

mple,theeye(Eye),theno(No),

themouth(Mouth)andtheear(Ear)arepartofthehead(Head),

soclassHeadshouldbemadeupofclassEye,No,Mouth,and

Ear,pleprogramisasfollows:

ClassEye

{

Public:

VoidLook(void);

};

ClassNo

{

Public:

VoidSmell(void);

};

ClassMouth

{

Public:

VoidEat(void);

};

ClassEar

{

Public:

VoidListen(void);

};

//correctdesign,alengthyprocess

ClassHead

{

Public:

VoidLook(void){m_()}

VoidSmell(void){m_()}

VoidEat(void){m_()}

VoidListen(void){m_()}

Private:

Eyem_eye;

Nom_no;

Mouthm_mouth;

Earm_ear;

};

IfHeadisallowedtoderivefromEye,No,Mouth,andEar,

thenHeadwillautomaticallyhavefunctionssuchasLook,Smell,

Eat,andListen:

//thewrongdesign

ClassHead:public,Eye,public,No,public,Mouth,public,

Ear

{

};

Theaboveprocedureisbriefandcorrect,butthedesignis

ogrammersareunabletoresistthetemptationto

"inherit"andmakedesignmistakes.

Acockistryinghardtocatchahenwhohasjustlaidanegg.

Doyouknowwhy?

Becauthehenlaidtheduckegg.

Inthe3.3ctionofthebook,aprogramthatrunscorrectly

anexample.

6.1.3virtualfunctionsandpolymorphism

Inadditiontoinheritance,anothergoodfeatureofC++is

supportforpolymorphism,thatallowsobjectsderivedfrom

he

baclass,BandCarethederivedclassofA,andthe

parameterofthepolymorphicfunctionTestisthepointerto

A.

ThentheTestfunctioncanreferenceobjectsofA,B,andC.

Thesampleprogramisasfollows:

ClassA

{

Public:

VoidFunc1(void);

};

VoidTest(A*a)

{

A->Func1();

}

ClassB:publicA

{

...

};

ClassC:publicA

{

...

};

//Example

(main)

{

Aa;

Bb;

Cc;

Test(&a);

Test(&b);

Test(&c);

};

Theaboveproceduredoesnotethevalueof"polymorphism",

plusthevirtualfunctionandabstractbaclass,the

"polymorphic"powerisdisplayed.

C++usthekeywordvirtualtodeclareafunctionasvirtual

function,andderivesthevirtualfunctionoftheclasstothe

functionofthevirtualfunctioncorrespondingtotheba

class(override).Thesampleprogramisasfollows:

ClassA

{

Public:

Virtual,void,Func1(void){cout<<,This,is,A::Func1,n}

};

VoidTest(A*a)

{

A->Func1();

}

ClassB:publicA

{

Public:

Virtual,void,Func1(void){cout<<,This,is,B::Func1,n}

};

ClassC:publicA

{

Public:

Virtual,void,Func1(void){cout<<,This,is,C::Func1,n}

};

//Example

(main)

{

Aa;

Bb;

Cc;

Test(&a);//ThisisA:output:Func1

Test(&b);//ThisisB:output:Func1

Test(&c);//ThisisC:output:Func1

};

IfthebaclassAisdefinedasfollows:

ClassA

{

Public:

VirtualvoidFunc1(void)=0;

};

ThenthefunctionFunc1iscalledapurevirtualfunction,and

aclasscontainingpurevirtualfunctionsiscalledanabstract

tractbaclasssimplydefinestheformof

purevirtualfunctions,andthespecificfunctionsare

implementedbyderivedclass.

Combiningtheabstractbaclassandpolymorphismhasthe

followingoutstandingadvantages:

(1)theapplicationdoesnothavetowritefunctioncallsfor

eachofthederivedclass,butonlytheabstractbaclass

Thename"statusquo",cangreatlyimprovethereusabilityof

theprogram(whichismultiplexedinterfacedesignreu

insteadofcode).

(2)thefunctionofaderivedclasscanbereferencedbythe

baclasspointer,whichiscalledbackwardcompatibility,

whichcanimprovetheextensibilityandmaintainabilityof

'snotsurprisingthatpreviouslywrittenprograms

canbeinvokedbyfuturewrittenprograms,butfutureprograms

'samazing.

6.2goodprogrammingstyle

Stronginternalskills,martialartsmastermovesofteninsipid.

Similarly,theprogrammingmasterwillnotuspecialtactics

rogrammingstyleisaprerequisite

forproducinghighqualityprograms.

6.2.1namingconvention

Manypeopleupinyintonamefunctionsorvariableswhen

esn'tmeanyou'repatriotic,butitmakes

lishintheprogram

willnotbetoocomplicated,andthewordsshouldbeexact.

Hungariannaminglawis[Maguire1993]advocatedbyMicrosoft

ghitisverycomplicated,itisnaturaltoget

orcedyoutoadoptanynomenclature,but

onethingshouldbedone:yourownprogramnamingmustbe

consistent.

ThefollowingisthenamingconventionIudwhenprogramming:

(1)macrodefinitionsarehighlightedinuppercaletters,

suchasMAX_LENGTH;

(2)functionsaremadeupofwordsbeginningwithupperca

letters,suchasSetName,GetName;

(3)pointervariablesplusprefixP,suchas*pNode;

(4)theBOOLvariableisprefixedwithB,suchasbFlag;

(5)theintvariableisprefixedwithI,suchasiWidth;

(6)thefloatvariableisprefixedwithF,suchasfWidth;

(7)thedoublevariableisprefixedwithD,suchasdWidth;

(8)stringvariablesplusprefixSTR,suchasstrName;

(9)enumeratesvariablesplusprefixe,suchaDrawMode;

(10)themembervariablesoftheclassareprefixedwithm_,

suchasm_strName,m_iWidth;

Forint,float,

Doublevariables,ifthemeaningofthevariablenameisvery

obvious,thendonotprefix,iables

suchasI,J,K,typefloat,three-dimensionalcoordinatesof

typeZ(x,y,etc.).

6.2.2usasrtions

ProgramsaregenerallydividedintoDebugandReleaversions,

andtheDebugversionisforinternaldebugging,andtheRelea

sthatasrtis

amacrothatworksonlyintheDebugversion,whichisudto

lowingisamemorycopy

programthat,whenrunning,willstopiftheasrtparameter

isfal.(usually,promptdialogwillshowwhereasrtwas

triggered).

Copy/memoryblocksdonotoverlap

Voidmemcpy(void,*pvTo,void,*pvFrom,size_t,size)

{

Void*pbTo=(byte*)pvTo;

Void*pbFrom=(byte*)pvFrom;

Asrt(pvTo!=NULL&&pvFrom!=NULL);

While(size->0)

*pbTo++=*pbFrom++;

Return(pvTo);

}

Asrtisnotahastilycobbledmacro,andasrtshouldnot

haveanysideeffectsinordernottodifferentiatebetweenthe

rt

isnotafunction,mmerscaneasrtas

aharmlesstesttoolthatcanbeudsafelyinanysystemstate.

Therearefewthingsmorefrustratingthantrackingthe

asrtionoftheprogramwithoutknowingtheeffectofthe

ndalotoftimenottryingtogetridofyour

mistakes,mes,

u

don'tknowwhattheasrtionis,it'shardtotellwhetherthe

ately,it's

agoodsolution,obvious,

'slikeamanintheforest,and

tisthedanger?

ThetreeisfallingdownThereisanabandoned?Wildanimals?

Unlessyoutellpeoplewhatthe"danger"is,thewarningcard

lligible

asrtionsareoftenignoredorevendeletedbyprogrammers.

[Maguire1993]

Hereareafewprinciplesforusingasrtions:

(1)uasrtionstocatchillegalsituationsthatshouldnot

'tconfuthedifferencebetweenanillegal

terisinevitableandmust

bedealtwith.

(2)uasrtionstoconfirmtheparametersofthefunction.

(3)whenwritingafunction,youmustexamineitrepeatedlyand

askyourlf,"whatassumptionsdoIintendtomake?""Once

established

Itisassumedthattheasrtionisudtocheckthe

assumptions.

(4)generaltextbookncourageprogrammerstoprogramerror

proofing,butrememberthatthisprogrammingstyleconceals

ti-errorprogrammingoccurs,ifthe

"impossible"thingdoeshappen,uanasrtiontoalarm.

6.2.3,new,delete,andpointers

InC++,theoperatornewisudtoapplymemory,andthe

language,the

functionmallocisudtoapplymemory,andthefunctionfree

eC++iscompatiblewiththeC

language,new,delete,malloc,andfreeareallpossibletou

domorethanmallocdoes,itcanapplyobject

memory,ntertotheC++andClanguage

inthepowerful,interP,

ifnewisudformemory,thendeletemustbeudinsteadof

ocisudformemory,thenfreemustbeud

singdeleteorfreetoreleathe

memorythatPrefersto,

而VisualBasic则将真定义为-1。示例程序如下:

布尔标志;

如果(旗){//做什么}//正确的用法

如果(==真旗){//做什么}//危险的用法

如果(旗==1){//做什么}//危险的用法

如果(!旗){//做什么}//正确的用法

如果(旗==fal){//做什么}//不合理的用法

如果(旗==0){//做什么}//不合理的用法

(4)小心不要将“==”“=”,编译器不会自动发现这种错误写成。

(5)不要将123写成0123,后者是八进制的数值。

(6)将自己经常犯的编程错误记录下来,制成表格贴在计算机旁边。

本文发布于:2022-11-24 01:43:51,感谢您对本站的认可!

本文链接:http://www.wtabcd.cn/fanwen/fan/90/9108.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

上一篇:hamimelon
下一篇:tomato的音标
标签:oriented
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图