计算机专业外文翻译_第1页
计算机专业外文翻译_第2页
计算机专业外文翻译_第3页
计算机专业外文翻译_第4页
计算机专业外文翻译_第5页
已阅读5页,还剩19页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

计算机专业外文翻译

毕业设计英文翻译作者:XXX

TheDelphiProgrammingLanguage

TheDelphidevelopmentenvironmentisbasedonanobject-oriented

extensionofthe

PcisealprogramminglanguageknownasObjectPascal.Mostmodern

programminglanguages

supportobject-orientedprogramming(OOP).OOPlanguagesarebased

onthreefundamental

concepts:encapsulation(usuallyimplementedwithclasses),

inheritance,andpolymorphism

(orlatebinding).

IClassesandObjects

DelphiisbasedonOOPconcepts,andinparticularonthedefinition

ofnewclasstypes.

TheuseofOOPispartiallyenforcedbythevisualdevelopment

environment,becausefor

everynewformdefinedatdesigntime,Delphiautomatical1ydefines

anewclass.Inaddition,

everycomponentvisuallyplacedonaformisanobjectofaclass

typeavailableinoraddedto

thesystemlibrary.

AsinmostothermodernOOPlanguages(includingJavaandC#),in

Delphiaclass-type

variabledoesn*tprovidethestoragefortheobject,butisonlya

pointerorreferencetothe

objectinmemory.Beforeyouusetheobject,youmustallocate

memoryforitbycreatinga

newinstanceorbyassigninganexistinginstancetothevariable:

var

Objl,0bj2:TMyClass;

begin//assignanewlycreatedobject

Objl:=TMyClass.Create;//assigntoanexistingobject

Obj2:=ExistingObject;

ThecalltoCreateinvokesadefaultconstructoravailableforevery

class,unlesstheclass

redefinesit(asdescribedlater).Todeclareanewclassdatatype

inDelphi,withsomelocal

datafieldsandsomemethods,usethefollowingsyntax:

type

TDate=class

Month,Day,Year:Integer;

procedureSetValue(m,d,y:Integer);

functionLeapYear:Boolean;

第1页共13页

毕业设计英文翻译作者:XXX

end;

2CreatingComponentsDynamically

ToemphasizethefactthatDelphicomponentsaren,tmuchdifferent

fromotherobjects

(andalsotodemonstratetheuseoftheSelfkeyword),I'vewritten

theCreateCompsexample.

Thisprogramhasaformwithnocomponentsandahandlerforits

OnMouseDownevent,

whichI'vechosenbecauseitreceivesasaparameterthepositionof

themouseclick(unlike

theOnClickevent).Ineedthisinformationtocreateabutton

componentinthatposition.Here

isthemethod'scode:

procedureTForml.FormMouseDown(Sender:TObject;

Button:TMouseButton;Shift:TShiftState;X,Y:Integer);

VarBtn:TButton;

begin

Btn:=TButton.Create(Self);

Btn.Parent:=Self;

Btn.Left:=X;

Btn.Top:=Y;

Btn.Width:-Btn.Width+50;

Btn.Caption:=Format(*Buttonat%d,%d*,[X,Y]);

end;

Theeffectofthiscodeistocreatebuttonsatmouse-click

positions,asyoucanseeinthe

followingfigure.Tnthecode,noticeinparticulartheuseofthe

Selfkeywordasboththe

parameteroftheCreatemethod(tospecifythecomponent'sowner)

andthevalueofthe

Parentproperty.

(Thaoutputoft.hnpxamplp,whichcrpatpsButtoneomponpnt.satrun

time

第2页共13页

毕业设计英文翻译作者:XXX

3Encapsulation

Theconceptofencapsulationisoftenindicatedbytheideaofa

“blackbox.〃Youdon,t

knowabouttheinternals:Youonlyknowhowtointerfacewiththe

blackboxoruseit

regardlessofitsinternalstructure.The〃howtouse"portion,

calledtheclassinterface,allows

otherpartsofaprogramtoaccessandusetheobjectsofthatclass.

However,whenyouuse

theobjects,mostoftheircodeishidden.Youseldomknowwhat

internaldatatheobjecthas,

andyouusuallyhavenowaytoaccessthedatadirectly.Ofcourse,

youaresupposedtouse

methodstoaccessthedata,whichisshieldedfromunauthorized

access.Thisisthe

object-orientedapproachtoaclassicalprogrammingconceptknownas

informationhiding.

However,inDelphithereistheextralevelofhiding,through

properties,

4PrivateProtectedandPublic

Forclass-basedencapsulation,theDelphilanguagehasthreeaccess

specifiers:private,

protected,andpublic.Afourth,published,controlsrun-timetype

information(RTTT)and

design-timeinformation,butitgivesthesameprogrammatic

accessibilityaspublic.Hereare

thethreeclassicaccessspecifiers:

,Theprivatedirectivedenotesfieldsandmethodsofaclassthat

arenotaccessibleoutside

theunitthatdeclarestheclass.

,Theprotecteddirectiveisusedtoindicatemethodsandfields

withlimitedvisibility.Only

thecurrentclassanditsinheritedclassescanaccessprotected

elements.Moreprecisely,

onlytheclass,subclasses,andanycodeinthesameunitasthe

classcanaccessprotected

members©

,Thepublicdirectivedenotesfieldsandmethodsthatarefreely

accessiblefromanyother

portionofaprogramaswellasintheunitinwhichtheyare

defined.

Generally,thefieldsofaclassshouldbeprivateandthemethods

public.However,this

isnotalwaysthecase.Methodscanbeprivateorprotectedifthey

areneededonlyinternal1y

toperformsomepartialcomputationortoimplementproperties.

Fieldsmightbedeclaredas

protectedsothatyoucanmanipulatethemininheritedclasses,

althoughthisisn'tconsidereda

goodOOPpractice.

SEncapsulatingwithProperties

第3页共13页

毕业设计英文翻译作者:XXX

PropertiesareaverysoundOOPmechanism,orawell-thought-out

applicationofthe

ideaofencapsulation.Essentially,youhaveanamethatcompletely

hidesitsimplementation

detai1s.Thisallowsyoutomodifytheclassextensivelywithout

affectingthecodeusingit.A

gooddefinitionofpropertiesisthatofvirtualfields.Fromthe

perspectiveoftheuseroftheclassthatdefinesthem,propertieslook

exactlylikefields,becauseyoucangenerallyreador

writetheirvalue.Forexample,youcanreadthevalueofthe

Captionpropertyofabuttonand

assignittotheTextpropertyofaneditboxwiththefollowing

code:

Edit1.Text:=Button1.Caption;

Itlookslikeyouarereadingandwritingfields.However,

propertiescanbedirectly

mappedtodata,aswellastoaccessmethods,forreadingand

writingthevalue.When

propertiesaremappedtomethods,thedatatheyaccesscanbepart

oftheobjectoroutsideof

it,andtheycanproducesideeffects,suchasrepaintingacontrol

afteryouchangeoneofits

values.Technically,apropertyisanidentifierthatismappedto

dataormethodsusingaread

andawriteclause.Forexample,hereisthedefinitionofaMonth

propertyforadateclass:

propertyMonth:IntegerreadFMonthwriteSetMonth;

ToaccessthevalueoftheMonthproperty,theprogramreadsthe

valueoftheprivate

fieldFMonth;tochangethepropertyvalue,itcallsthemethod

SetMonth(whichmustbe

definedinsidetheclass,ofcourse).

Differentcombinationsarepossible(forexample,youcouldalsouse

amethodtoread

thevalueordirectlychangeafieldinthewritedirective),but

theuseofamethodtochange

thevalueofapropertyiscommon.Herearetwoalternative

definitionsfortheproperty,

mappedtotwoaccessmethodsormappeddirectlytodatainboth

directions:

propertyMonth:IntegerreadGetMonthwriteSetMonth;

propertyMonth:IntegerreadFMonthwriteFMonth;

Often,theactualdataandaccessmethodsareprivate(orprotected),

whereastheproperty

ispublic.Forthisreason,youmustusethepropertytohaveaccess

tothosemethodsordata,a

techniquethatprovidesbothanextendedandasimplifiedversionof

encapsulation.Itisan

extendedencapsulationbecausenotonlycanyouchangethe

representationofthedataandits

accessfunctions,butyoucanalsoaddorremoveaccessfunctions

withoutchangingthe

callingcode.Auseron1yneedstorecompi1etheprogramusingthe

property.

第4页共13页

毕业设计英文翻译作者:XXX

6PropertiesfortheTDateClass

Asanexample,Vveaddedpropertiesforaccessingtheyear,the

month,andthedaytoan

objectoftheTDateclassdiscussedearlier.Thesepropertiesare

notmappedtospecificfields,

buttheyal1maptothesinglefDatefieldstoringthecompletedate

information.Thisiswhy

allthepropertieshavebothgetterandsettermethods:

type

TDate=class

public

propertyYear:IntegerreadGetYearwriteSetYear;

propertyMonth:IntegerreadGetMonthwriteSetMonth;

propertyDay:IntegerreadGctDaywriteSctDay;

Eachofthesemethodsiseasilyimplementedusingfunctions

avai1ableintheDateUti1s

unit.Hereisthecodefortwoofthem(theothersareverysimilar):

functionTDate.GetYear:Integer;

begin

Result:=YearOf(fDate);

end;

procedureTDate.SetYear(constValue:Integer);

begin

fDate:=RecodeYear(fDate,Value);

end;

7AdvancedFeaturesofProperties

PropertieshaveseveraladvancedfeaturesIHereisashortsummary

ofthesemore

advancedfeatures:

,Thewritedirectiveofapropertycanbeomitted,makingita

read-onlyproperty.The

compilerwillissueanerrorifyoutrytochangethepropertyvalue.

Youcanalsoomitthe

readdirectiveanddefineawrite-onlyproperty,butthatapproach

doesn,tmakemuchsenseandisusedinfrequently.

第5页共13页

毕业设计英文翻译作者:XXX

,TheDelphiIDEgivesspecialtreatmenttodesign-timeproperties,

whicharedeclaredwiththepublishedaccessspecifierandgenerally

displayedintheObjectInspectorforthe

selectedcomponent..

,Analternativeistodeclareproperties,oftencalledrun-time

onlyproperties,withthepublicaccessspecifier.Thesepropertiescan

beusedinprogramcode.

,Youcandefinearray-basedproperties,whichusethetypical

notationwithsquare

bracketstoaccessanelementofalist.Thestringlist-based

properties,suchastheLinesofalistbox,areatypicalexamplecf

thisgroup.

,Propertieshavespecialdirectives,includingstoredanddefaults,

whichcontrolthe

componentstreamingsystem.

8EncapsulationandForms

Oneofthekeyideasofencapsulationistoreducethenumberof

globalvariablesusedby

aprogram.Aglobalvariablecanbeaccessedfromeveryportionofa

program.Forthisreason,

achangeinaglobalvariableaffectsthewholeprogram.Onthe

otherhand,whenyouchange

therepresentationofaclass'sfield,youon1yneedtochangethe

codeofsomemethodsofthat

classandnothingelse.Therefore,wecansaythatinformation

hidingreferstoencapsulating

changes.

Letmeclarifythisideawithanexample.Whenyouhaveaprogram

withmultipleforms,

youcanmakesomedataavailabletoeveryformbydeclaringitasa

globalvariableinthe

interfaceportionoftheunitofoneoftheforms:

var

Forml:TForml;

nClicks:Integer;

Thisapproachworks,butthedataisconnectedtotheentireprogram

ratherthana

specificinstanceoftheform.Ifyoucreatetwoformsofthesame

type,they'11sharethedata.

Ifyouwanteveryformofthesametypetohaveitsowncopyofthe

data,theon1ysolutionis

toaddittotheformclass:

type

TForml=class(TForm)

第6页共13页

毕业设计英文翻译作者:XXX

public

□Clicks:Integer;

end;

9AddingPropertiestoForms

Thepreviousclassusespublicdata,soforthesakeof

encapsulation,youshouldinstead

changeittouseprivatedataanddata-accessfunctions.Aneven

bettersolutionistoadda

propertytotheform.Everytimeyouwanttomakesomeinformation

ofaformavailableto

otherforms,youshoulduseaproperty,foral1thereasons

discussedinthesection

''EncapsulatingwithProperties.Todoso,changethefield

declarationoftheform(inthepreviouscode)byaddingthekeyword

propertyinfrontofit,andthenpressCtrRShift+Cto

activatecodecompletion.Delphiwillautomaticallygenerateallthe

extracodeyouneed.

propertiesshouldalsobeusedintheformclassestoencapsulate

theaccesstothe

componentsofaform.Forexample,ifyouhaveamainformwitha

statusbarusedtodisplay

someinformation(andwiththeSimplePanelpropertysettoTrue)and

youwanttomodifythe

textfromasecondaryform,youmightbetemptedtowrite

Forml.StatusBarl.SimpleTcxt:='newtext';

ThisisastandardpracticeinDelphi,but.it'snotagoodone,

becauseitdoesn*tprovide

anyencapsulationoftheformstructureorcomponents.Ifyouhave

similarcodeinmany

placesthroughoutanapplication,andyoulaterdecidetomodifythe

userinterfaceoftheform

(forexample,replacingStatusBarwithanothercontroloractivating

multiplepanels),you,11

havetofixthecodeinmanyplaces.Thealternativeistousea

methodor,evenbetter,a

propertytohidethespecificcontrol.Thispropercanbedefined

as

propertyStatusText:stringreadGetTextwriteSetText;

withGetTextandSetTextmethodsthatreadfromandwritetothe

SimpleTextproperty

ofthestatusbar(orthecaptionofoneofitspanels).Inthe

programs?otherforns,youcan

refertotheform,sStatusTextproperty;andiftheuserinterface

changes,onlythesetterand

gettermethodsofthepropertyareaffected.

第7页共13页

毕业设计英文翻译作者:XXX

Delphi开发环境是基于Pascal编程语言ObjectPascal的面向对象的一种扩

展。大多数现代编程语言都支持面向对象编程(OPP)。OPP语言基于三个基本概

念:封装(通

常通过类实现)继承、多态。

1、类与对象

Delphi是基于OPP蹴念的,特别是在新类类型中。OPP的使用在可视开发环境

中得到了增强,这是因为,对于每个在设计时定义的一个新窗体来说,Delphi会自动

定义一个新的类。另外,每个可视放置在一个窗体中的组件实际上是T类型对象,而且该

可以在系统库中获得,或者被添加到系统库中。

就像大多数开创现代OPP语言(包括Java和C#)中一样,在Delphi中,一个

类的类型变量为对象提供存储,而只是在内存中为对象提供一个指针或引用。在使用

对象之

前,必须创建一个新的实例或将一个现有的实例分配给变量,以此来为其分配

内存:

var

Objl,Obj2:TMyClass;

begin//assignanewlycreatedobject

Objl:=TMyClass.Create;//assigntoanexistingobject

Obj2:=ExistingObject;

对Create的调用会激活一个默认的构造器,该构造器对每个类都有效,除非

某个

类重新定义了它。为了在Delphi中声明一个新的带有一些本地数据字段的和

一些方法

的类数据类型,可使用下面的语法:

type

TDate=class

Month,Day,Year:Integer;

procedureSetValue(m,d,y:Integer);

functionLeapYear:Boolean;

end;

动态的创建组件

第8页共13页

毕业设计英文翻译作者:XXX

为了强调Delphi组件与其他对象没有太多的区别的事实(同时说明Self关键

字口

使用)的使用方法,笔者编写了一个CreateComps范例。这个程序有一个不带

组件的窗体和一个用语其OnMouseDown事件的处理器,之所以选择它是以为它将鼠

标单机的位置

作为一个参数接收(与OnClick事件不同)。我们需要这个信息,以便在那个

位置创建

有个按钮组件。下面是该方法的代码:

procedureTForml.FormMouseDown(Sender:TObject;

Button:TMouseButton;Shift:TShiftState;X,Y:Integer);

var

Btn:TButton;

begin

Btn:=TButton.Create(Self);

Btn.Parent:=Self;

Btn.Loft:=X;

Btn.Top:=Y;

Btn.Width:=Btn.Width+50;

Btn.Caption:=Format(JButtonat%d,%d*,[X,Y]);

end;

这段代码的作用是在鼠标单击的位置创建按钮,正如在下图中看到的那样,在

该代

码中,特别要注意Self关键字的使用??同时作为Create方法的参数(以指定

组件的所有者)和Parent属性的值。

1QJ2SJ

Buttonat65,80

Buttonat202,120

Buttonat85,178

CreateCompsr的示列输出,用于在运行时创建按钮组件

封装的概念简单,可以把其想象为一个“黑盒子”.人们并不知道其内部什

么:只

能知道牌位与黑例子接口,或使用它而其内部结构。“怎样使用”这部分,称

为类的接

口,它允许程序的其他部分访问和使用该类的对象。然而,使用对象时,对象

的大部分

第9页共13页

毕业设计英文翻译作者:XXX

代码都是隐含的。用户很少能知道对象胡哪些内部数据,而且一般没有办法可

以直接访

问数据。可以使用对象方法来访问数据,这与非法的访问不同。相对于信息隐

含这样一

个经典的编程概念来说,这就是面向对象的方法。然而,然而Delphi中,通

过属性会有其他等级的。

对基于类的封装来说,Delphi使用了三个访问标识符:PrivateProtccted和

Public第四个地Published,控制着运行时的类型信息(RTTI)和设计时信

息,但是它提供了和Public相同的程序访问性。这里是三个经典的访问标识符。

a)Private指令专门用于一个类字段和对象方法在声明类的单元外的类不能被

访

问。

b)Protected指令用于表示对■象方法和字段具有有限的可见性。Protected元

素只能被当前类和它的子类访问。更精确地说,只71同一个单元中的类、子类和任何代码可

以访问protected成员。

c)Public指令专门用于表示那些可以被程序代码中的任意部分高谈阔论的数

据和

对象方法,当然也包括在定义它们的单元。

一般情况下,一个类的字段应该是专用的,而对象方法则应该是公用的。然而

如果

某对象方法只需要在内部完成一些部分或实现属性,那么该方法也可以是专用

或受难保

护的。字段可以被声明为受难,这样就可以在子类中对它们进行处理,尽管这

并不是一

个好的OPP行为。

属性是一种非常能够有效的OOP机制,或者说非常适合实现封装的思想。从本

质上

讲,书信就是用一个名称来完全隐藏它的实现细节,这使得程序员可以任意修

改类,而

还会影响使用它的代码。关于什么是属性,有一个较好的定义,亦即属性就是

字段。从

定义它们的类的用户角度来看,属性完全就像字段一样,因为拥护可以读取或

编写它们

的值。例如,可以用以下代码读取一个按钮的Caption属性值,并将其赋给一

个带有下写代码的编辑筐的text属性:

Editl.Text:=Buttonl.Caption;

这看起来就像读写字段一样。然而,属性可以直接与数据以及访问对象的方法

对应

起来,用于读写数值。当属性对象方法对应时,访问的数据可以是对象或其外

部和某部

第10页共13页

毕业设计英文翻译作者:XXX分内容,而且它们可以产生附加影响,如在改

变了一个属性值后,提亲绘制一个控件。

从技术上讲,一个属性就是对应数据或对象方法(使用一个read或一个子

句)的标识符。例如,下面是一个日期类的Month属性的定义:

Propertymonth:IntegerreadFMonthwriteSetMonth;

为了访问Month属性的值,该程序语句要读取专用字段FMonth的值,同时为其

改变该属性值,它调用了对象方法SetMonth(当然,必须在类的内部定义它)。

不同的组合都是可能的(例如,还可以使用一个对象方法来读取属性值或直接

修改

write指令中的一个字段),但使用对象方法修改一个属性的值是很觉的。下

面是属性的

两种可替换定义,它们分别对应两个访问方法或在两个方向上直接对应着数

据:

propertyMonth:IntegerreadGetMonthwriteSetMonth;

propertyMonth:IntegerreadFMonthwriteFMonth;

通常,属性是公共的。而实际数据与访问对象方法是专用的(或受保护的),

这意

味着必须使用属性访问那些对象方法或数据,这种技术提供了封装的扩展简化

版本。它

是一个扩展的封装,不但可以改变数据的表示方法与访问函数,而且还可以添

加与删除

访问函数。而还会影响到调用代码。一个用户只重新编译使用属性的程序即

可。6TDate

作为一个范例,我向前面讨论过的TDate类的一个对象中添加用于访问年、

月、日

的属性。这些属性参与特定的字段对应着存储完整日期信息的单个TDate字

段。这就是所有属性都有getter和setter方法的原因;

type

TDate=class

public

propertyYear:IntegerreadGet

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论