Object pascal语法

OBJECTPASCALPROGRAMING(WRITEDBYC.Y.CATTENTIONSYSTEMDEVELOPMENTCO,.)
1.标记(TOKEN)
1.1特别符号(Symbols)
字母(Letters):A..Z,a..z
数字(Digits):0..9
十六进位数字(HexDigits):0..9,A..F(ORa..f)
空白(Blank):ASCII32
单字元符号:+-*/=<>[].,():;^@{}$#
多字元符号:<=,>=,:=,..,(*,*),(.,.)

1.2识别字(Identifiers)
表示:常数,型态,变数,程序,函数,程式单元,程式,栏位....
长度:63位内有效,不分大小写
字首:字母,_
识别字不得重复,若有重复必需采限定识别字:Unit1.IdentName

1.3标笺(Label):0..9999or识别字

1.4字元字串
'ATTN'-----------ATTN
'You''llsee'----Yoy'llsee
''---------------空字串
''--------------空白字元
'Line1'#13#10'Line2'------Line1
Line2
1.5注释
{xxxxxxx}

{xxxxxxxx
xxxxxx
xxxxx}

//xxxxxxxx

2.常数宣告(使用标记=)
2.1一般常数宣告
CONST
Min=0;
Max=100;
Center=(Max-Min)Div2;
Blank=Chr(32);
NumChr=Ord('Z')-Ord('A')+1;
ErrMsg='OutOfRang';
ErrDtl='OutOfRang'+':Item10';
Numeric=['0'..'9'];
Alpha=['A'..'Z','a'..'z'];
AlphNum=Alpha+Numeric;
2.1型态常数(Typedconstant)宣告
CONST
MaxInt:Integer=9999;
FixReal:Real=-0.12;
ListStr:String[4]='This';
AA:Pchar='abcedf';
Dim:Array[0..1,0..1,0..1]ofInteger=(((0,1),(2,3)),((4,5),(6,7)));
{Dim(0,0,0)=0Dim(0,0,1)=1
Dim(0,1,0)=2Dim(0,1,1)=3
Dim(1,0,0)=4Dim(1,0,1)=5
Dim(1,1,0)=6Dim(1,1,1)=7}
--------------------------------
TYPE
Trec=record
fl1,fl2:Integer;
end;

CONST
IntRec:Trec=(fl1:1;fl2:2);
------------------------------------------


3.型态宣告(使用标记=):当宣告一个变数时,必须指明其型态
3.1例子(1)
TYPE
Trang=Integer;
TNumber=Integer;
TColor=(Red,Green,Blue);
TCharVal=Ord('A')..Ord('Z');
TtestIndex=1..100;
TtestValue=-99..99;
TtestList=Array[TtestIndex]ofTtestvalue;
ptestList=^TtestList;=>指标型态
Tdate=Class
Year:Integer;
Month:1..12;
Day:1..31;
ProcedureSetDate(D,M,Y:Integer);
FunctionShowDate:String;
end;
TMeasureList=Array[1..50]ofTMeasuredate;
Tname=String[80];=>定长度
Tsex=(Male,Female);=>01
PpersonData=record
Name,FirstName:Tname;
Age:Integer;
Married:Boolean;
TFather,TChild,TSibling:PPersonData;
Cases:Tsexof=>0和1之间
Maie:(Bearded:Boolean);
Female:(Pregnant:Boolean);
End;
TPersonBuf=Array[0..Size(TPsersonData)-1]ofByte;
TPeople=FileOfTPersonData;=>定type


3.2简单型态
3.2.1序数型态
(1)整数型态:
基础型态(Fundmental)
Shortint-128..1278-bit
Smallint-32768..3276716-bit
Longint-2147483648..214748364732-bit
Byte0..2558-bit
Word0.6553516-bit
通用型态(Generic)
Integer-2147483648..214748364732-bit
Cardinal0..214748364732-bit
若16bit
Integer-32768..3276716-bit
Cardinal0.6553516-bit

(2)字元型态
基础型态(Fundmental)
AnsiCharASCII1-Byt
WideCharUnicode2-Byt
通用型态(Generic)
CharASCII1-Byt

(3)列举型态(EnumeratedType)
==============================================
TColor=(Red,Green,Blue);
==============================================

(4)逻辑型态(BooleanType)
基础型态(Fundmental)
ByteBool0..11-Byt
WordBool0..12-Byt
LongBool0..14-Byt
通用型态(Generic)
Boolean1-Byt
==============================================
Married:Boolean;

False<True
Ord(False)=0
Ord(True)=1
Succ(False)=True
Pred(True)=False
==============================================

(5)子集型态(Subrangtype)
==============================================
TtestIndex=1..100;
==============================================
3.2.2实数型态
型态有效位数位元组大小
Real11-126
Single7-84
Douible15-168
ExTended10-2010
Comp19-208
Currency19-208
===================================================
例子Real6byt共48bit

1-12-4041-48
sfe
有效值v
if(e>0)and(e<=255)then
v=(-1)**s*2**(e-129)*(1.f)
elseife=0thenv=0;
===================================================

3.3字串型态
3.3.1基础型态(Fundmental)
(1)ShortString短字串1-255(又称pascalstring)
(2)AnsiString长字串1-2G
(3)PChrNull-Terminatedstring

3.3.2通用型态(Generic)
String32位元时等於AnsiString
16位元时等於ShortString
===================================================
(1)字串为一以零为基底的字元阵列(Zero-basecharacterarray)

-----------------------
TYPE
TStringBuf=Array[0..79]ofChar;
const
StringBuf:TStringBuf='Thisistest';
-----------------------

(2)vars:ShortString
Length(s)=Ord(s[0])
(3)长字串以4-byt指标,指到动态配置之记忆体,没有[0]之长度数值
一个动态记忆体配置之长字串会自动以一空字元(nullCharacter)结束
(4)PChr以字元阵列来储存,结尾以(nullCharacter)结束,使用指标来管理
(5)PChr型态与String型态在指定叙述上是相容
例:
-----------------------------
varp:pchr;

begin
p:='thisistest';
end;
-----------------------------
ProcedurePrintStr(Str:Pchr);

呼叫时可用
PrintStr('Thisistest');
-----------------------------

3.4结构型态(Stricturedtype)
3.4.1阵列型态(Arraytype)
TDim1=Array[0..79]ofChar;
TDim2=Array[1..3,1..10]ofChar;

VAR
Dim1:Tdim1;
I:Integer;
begin

forI:=Low(Dim1)toHigh(Dim1)do
Dim1[I]:=#32;


end;
===================================================
3.4.2记录型态(RecordType)
TYPE
TdateRec=Record
Year:Integer;
Month:1..12;
Day:1..31;
end;

何谓变动栏位?

3.4.3集合型态(SetType)
TYPE
Tmenber=(Lee,White,Ston);
Tmenbers=SetOfTmenber;


varMembers:Tmenbers;

begin
Menbers:=[White,Ston];

end;

集合型态不能超过256个可能值

3.4.4档案型态(FileType)
(1)记录型态档案
TYPE
Temployee=record
name:string[10];
address:string[50];
end;
TemployeeFile=FileOfTemployee;

var
EmployeeFile:TemployeeFile;

同EmployeeFile:FileOfTemployee;

(2)文件型态档案

TMyTextFile=TextFile;
var
MyTextFile:TMyTextFile;
or
MyTextFile:TextFile;

ReadText:String;

-----------------------------
AssignFile(MyTextFile,'c:\MyFile.txt');
Reset(MyTextFile);
WhileNotEof(MyTextFile)do
begin
Readln(MyTextFile,ReadText);


end;
CloseFile(MyTextFile);

注:Rewrite(MyTextFile);开启唯写
Writeln(MyTextFile,ReadText);

(3)其它型态档案
TBook=FileOfChar;
TnumFile=FileOfInteger;

3.4.5类别型态(ClassType)

TDBText=class(TCustomLabel)
private
FDataLink:TFieldDataLink;
procedureDataChange(Sender:TObject);
functionGetDataField:string;
functionGetDataSource:TDataSource;
functionGetField:TField;
functionGetFieldText:string;
procedureSetDataField(constValue:string);
procedureSetDataSource(Value:TDataSource);
procedureCMGetDataLink(varMessage:TMessage);messageCM_GETDATALINK;
protected
functionGetLabelText:string;override;
procedureNotification(AComponent:TComponent;
Operation:TOperation);override;
procedureSetAutoSize(Value:Boolean);override;
public
constructorCreate(AOwner:TComponent);override;
destructorDestroy;override;
propertyField:TFieldreadGetField;
published
propertyAlign;
propertyAlignment;
propertyAutoSizedefaultFalse;
propertyColor;
propertyDataField:stringreadGetDataFieldwriteSetDataField;
propertyDataSource:TDataSourcereadGetDataSourcewriteSetDataSource;
propertyDragCursor;
propertyDragMode;
propertyEnabled;
propertyFont;
propertyParentColor;
propertyParentFont;
propertyParentShowHint;
propertyPopupMenu;
propertyTransparent;
propertyShowHint;
propertyVisible;
propertyWordWrap;
propertyOnClick;
propertyOnDblClick;
propertyOnDragDrop;
propertyOnDragOver;
propertyOnEndDrag;
propertyOnMouseDown;
propertyOnMouseMove;
propertyOnMouseUp;
propertyOnStartDrag;
end;

元件之可见性
注-1:同一unit中Private,Protect,Public,published皆同Public
不同unit时其特性不同
Private:所属unit才有可见性
Protect:只有继承时才有可见性
Public:所有uses者皆有可见性
published:所有uses者皆有可见性,且提供元件设计时之栏位可见性
注-2:若宣告没有注明4P,则表示

3.5指标型态(Pointertype)
3.5.1字元指标(characterpointer)
在systemunit中,有下列宣告
TYPE
PAnsiChar=^AnsiChar;
PWideChar=^WideChar;
PChar=PAnsiChar;
所以在2.0版中,PChar和PAnsiChar是一样的

3.5.2通用指标
TYPE
TMyPointer=Pointer;
通用指标可以被型态转换後来参考


3.6程序型态(Proceduretype)
3.6.1全域程序指标
TYPE
TStrProc=Procedure(Consts:String);
TMyFunc=Function(X:Integer):String;
3.6.2方法程序指标
TYPE
TNotifyEven=Procedure(Sender:Tobject)ofObject;

3.6.3程序数值
一个程序型态变数可以被指定程序数值
TYPE
TMainForm=Class(TForm)
ProcedureButtonClick(Sender:Tobject);

end;

VAR
MyForm:TMainForm;
MyFunc:TMathFunc;



FunctionChgFunc(X:Integer):Integer;Far;
Begin
Result:=X+X;
end;


MyFunc:=ChgFunc;
X:=MyFunc(X);{等於X:=ChgFunc(X)}

==========================================

一个程序变数未被指定数值时其数值是nil,
但未被指定数值之程序或函数不能执行,
故安全之呼叫是
IfAssigned(OnClick)ThenOnClick(Self);


3.7变动型态(Varianttype)
(1)变动型态和其它型态一起使用会作自动型态转换=>使用arrey
Var
V1,V2,V3,V4,V5:Variant;
I:Integer;
D:Double;浮点
S:String;
Begin
V1:=1;
V2:=1234.5678;
V3:='Thisistest';
V4:='1000';
V5:=V1+V2+V4;{实数2235.5678}
I:=V1;{I=1}
D:=V2;{D=1234.5678}
S:=V3;{S='Thisistest'}
I:=V4;{I=1000}
S:=V5;{S='2235.5678'}
end;

虽然变动型态提供很大弹性,但它耗用更多记忆体,也比静态型态来得慢

(2)变动阵列
var
A:Variant;=>变动型态
I:Integer;
Begin
A:=VarArrayCreate([0,4],VarOleStr);
ForI:=0to4DoA[I]:='AAAA';
VarArrayRedim(A,9);=>加大
ForI:=5to9DoA[I]:='BBBB';

end;

4.变数宣告(使用标记:):当宣告一个变数时,必须指明其型态
4.1例子
X,Y,Z:Double;
I,J,K:Integer;
Dig:0..9;
C:Color;
Done,Error:Boolean;=>通常为一个byts
Operater:(Plus,Munus,Times);
H1,H2:SetOfColor;
Today:Date;
MyDim:Array[1..10,1..5]OfDouble;
4.2全域变数:在程序和函数之外宣告之变数
4.3区域变数:在程序和函数之内宣告之变
4.3变数初始化值:MyInt:Integer=123;{注意不可为区域变数指定初值}
4.4限定词:
4.4.1阵列索引:MyDim[I][J]同MyDim[I,J]
4.4.2栏位指示词:MyRec.MyField{在一个with叙述中可以省略栏位指示参考
4.4.3物件指示词:form1.Button1.Caption
4.4.4指标和动态变数:p1^,@p1
4.5变数型态转换
{例-1}
TYPE
TbyteRec=record
Fl1,Fl2:Byte;
end;

VAR
W:Word;
B:Byte;

Begin
W:=256*10+128;
B:=TbyteRec(W).Fl1;{B=10}
***word─────>换成byte型态
B:=TbyteRec(W).Fl2;{B=128}

end;
{例-2}
WithSenderasMdbeditdo=>代上一层型态
Text:='Thisistest';
{例-3}
Mdbedit(Sender).Text:='Thisistest';

5.运算式语法
5.1运算元及运算优先次序
(1)@,not单运算子运算元=>@变数住置
(2)*,/,div,mod,and,shl,shr,as乘除
(3)+,-,or,xor加减
(4)=,<>,<,>,<=,>=,in,is关系
5.2()有优先运算评量, 由内外之运算优先
5.3相同优先次序,则由左至右之运算优先
5.4捷径评量(short-Circuit)

while(I<=Length(S))and
(S[I]<>'')do
Inc(I)

捷径评量严格执行由左至右之运算,一旦运算结果己可知後便停止,可使得
一些原本不合法之运算架构变成可以运算
5.5运算元分类
5.5.1数学运算元:+,-,*,/
div整数相除之商
mod整数相除之余数
{ImodJ=I-(IdivJ)*J}

5.5.2逻辑运算元:not,And,Or,Xor,Shl,Shr

5.5.3字串运算元:+
S:='aaaaa'+'bbbb';{s=aaaaabbbb}

5.5.4集合运算元:+,-,*
+:连集-:差集*:交集

5.5.5关系运算元:=,<>,<,>,<=,>=,in=>in判断有效值
In:成员

type
Month=(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec);
Spring=setofFeb..Apr..Mar;
Mstr=array[0..11]ofstring[3];
const
CMstr:Mstr=('Jan','Feb','Mar','Apr','May', 'Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var
M:Month;
SSpring:Spring;
begin
SSpring:=[Feb..Apr];
writeln('TheSpringMonthis:');
forM:=JantoDecdo
ifMinSSpringthen
writeln(CMstr[Ord(M)]);
end;

5.5.6类别运算元:is,As
if(SenderisMbutten)and
(Mbutten(Sender).tag<>0)then...;

withSenderAsMdbeditdo
text:='aaaaaa';

5.5.7位置运算元:@
5.5.8指标运算元:^
var
M,N:integer;
P1,P2:^integer;=>指标
begin
M:=6;
P1:=@M;=>@位置
Label1.Caption:='P1^='+IntToStr(P1^);
P2:=P1;
N:=P2^;
Label2.Caption:='N='+IntToStr(N);
end;

6.叙述语法
6.1goto

labelaa;
vari:integer;
begin
.
.
if(i=0)thengotoaa;

aa:begin
.
.
end;
end;

6.2if

if(x>10)and{注意关系运算必须()}
(y>5)then
z:=x+y{注意没;}
elsez:=2*(x+y);
6.3case
var
s:string;
r:integer;
begin
ifs<>''then
begin
cases[1]of=>S之第一个BYTE
'1':r:=1;=>由小到大
'2':r:=2;
'3':r:=3;
elser:=4;
end;
end;

6.4while
While(i>0)do
begin
x=X+I;
I=I-1;
end;

whileTruedo
begin
if(i=0)thenbreak;=>break中断
x=X+I;
I=I-1;
end;
6.5Repeat=>先做再检查
repeat
k:=imodj;
i:=j;
j:=k;
untilj=0;

6.6for
fori:=1to10do
begin
ifi=5thencontinue;
x:=X+I;
end;

7.程式区块
7.1单元结构
unit<单元名称>
interface{界面部份}
uses<listofunits>;
{publicdeclarations}

Implementation{实作部份}
uses<listofunits>;
{Privatedeclarations}

{implementationofprocedureandfunction}

end.
7.2单元叫用
uses<unitnamelist>;
unitname会自动加上延伸档名.dcu
其它单元己编释过,故不是includesourcefile方式
若使用单元有使用到相同变数,必须采限定识别
unit.IdName

7.3间接单元参考
programprog;
usesunit1;
consta=b;
begin
end.

unitunit1;
interface
usesunit2;
constb=c;
implementation
end.


unitunit2;
interface
constc=1;
implementation
constd=2;
end.

7.4单元间交互参考
允许交互参考,但不能产生循环参考(Circularunitreferences),若有发生必
须有一单元之uses放在implementation下

programprog;
usesunit1;
consta=b;
begin
end.

unitunit1;
interface
usesunit2;
constb=c;
implementation
end.


unitunit2;
interface
constc=1;
implementation
usesunit1;{避开循环参考}
constd=b;
end.
8.程序与函式
8.1程序:procedure程序名(参数;参数..);
label{标记宣告}
type{型态定义}
var{变数宣告}
procedure
function
begin

{exit;}

end;
例如:Procedureprint(pStr:String);
begin
writeln(Pstr);
end;


8.2函数:function程序名(参数;参数..):传回资料型态;
label{标记宣告}
const{常数定义}
type{型态定义}
var{变数宣告}
procedure
function
begin

{exit;}

end;

例如functionadd(n1,n2:Integer):Integer;
begin
add:=n1+n2;
{result:=N1+N2;}
end;
8.3传值呼叫与传址呼叫
procedureAdd(Varsum:Integer;n1,n2:integer);
begin---{传址识别字}
sum:=n1+n2;
n1:=0;
n2:=0;
end;

proceduretest;
var
sum,a,b:integer;
begin
a:=100;
b:=200;
add(sum,a,b);{sum=300,a=100,b=200}
end;
8.3forward(前置宣告)
前置宣告不须使用在interface之公有宣告!,公有宣告形同forword作用
procedureadd(Varsum:integer;n1,n2:integer);forward;

procedurebase;
varsum:integer;
begin
add(sum,4,5);

end;

procedureadd(Varsum:integer;n1,n2:integer);
begin
sum:=n1+n2;
end;
8.4External(外部函数宣告)

FunctionMessageBox(Hwnd:Integer;
text,caption:Pchar;
Flags:Integer):Integer;Stdcall;
external'User32.dll'Name'MessageBoxa';

8.5呼叫惯例
编译器指令次序清除呼叫惯例
register由左至右函数使用暂存器pascal
pascal由左至右函数使用堆叠pascalorc
cdecl由右至左呼叫者使用堆叠pascalorc
stdcall由右至左函数使用堆叠WindowsApi

9.例外处理
9.1raise(引发)
注意-1:raise启动一个物件,而不是一个物件,通常呼叫例外类别的Create
来快速建立
例:SysUtilsExecption
constructorException.Create(constMsg:string);
begin
FMessage:=Msg;
end;


constructorException.CreateFmt(constMsg:string;
constArgs:arrayofconst);
begin
FMessage:=Format(Msg,Args);
end;

--------------------------------------------------
FunctionStrToIntRange(Vars:string;Min,Max:Longint):Longint;
begin
Result:=StrToInt(s);
If(Result<Min)or
(result>Max)then
raiseERangeError.CreateFmt(%disnotwithinthevalidrangeof%d..%d',
end;[result,Min,Max]);

注意-2:控制不会从一个raise叙述中回传,但在例外程式区块中允许再度
引发例外,

9.2Try...Except
语法
try
.
.
except
onErrorclass1do..;
onErrorclass2do..;
onErrorclass3do..;
else
{otheshandle...};
end;

没有on...do之语法
try
.
.
except
{exceptionhandle}
end;
例子-1
try
result:=sumdivnum;
except
onEZeroDividedoresult:=0;
onEOverFlowdoresult:=0;
onEMatherrordoresult:=0;
{由上而下检查择一处理,注意各种错误类别间之继承顺序}
else
result:=0;
end;

9.3Try...Finally
例:
reset(F);
try
processFile(F);
finally
closeFile(F);
end;

9.4exit,break,continue与try..finally之运作
例:
procedureTForm1.MButton1Click(Sender:TObject);
var
I:integer;
s:string;
begin
I:=10;
s:='正常结束!';
try
whileI<>0do
begin
I:=I-1;
ifI=5then
begin
s:='exit结束';
exit;
end;
end;
finally
Showmessage(s);{显示exit结束}
end;
end;

10.DLL(动态库}
10.1DLL特徵
project使用之单元是采静态连结(StaticallyLinked),而DLLs采动态连结
(DynamicallyLinked),故Projectl中并包含DDLs之拷贝

DLLs可用任何遵守windowsDLL之开发工具来开发或使用,适合多种开发工具
同时开发环境

10.2DLL使用
(1)藉由名称(循序寻找)
ProcedureImportByName;External'TestLib.dll';
(2)藉由重新名称
ProcedureImportByNewName;
External'TestLib.dll'name'ImportByName';
(3)藉由序号(找到程式的最快方法)
ProcedureImportByOrdName;
External'TestLib.dll'Index1;

(4)WindowsApi之呼叫
FunctionMessageBox(Hwnd:Integer;Text,Caption:Pchr
Flags:Integer):Integer;Stdcall;
External'User32.dll'Name'MessageBox';


(5)动态库之输入程式单元
(例-1):Delphi之开发环境中之useswindows
(例-2):
unitDateTime;{动态库之输入程式单元}
interface
type
TTimeRec=Record
ss:integer;
mi:Integer;
hh:Integer;
end;
type
TDateRec=Record
yy:Integer;
mm:Integer;
dd:Integer;
end;

ProcedureSetTime(VarTime:TTimeRec);
ProcedureGetTime(VarTime:TTimeRec);
ProcedureSetDate(VarDate:TDateRec);
ProcedureGetDate(VarDate:TDateRec);

Implementation
ProcedureSetTime;External'DATETIME'index1;
ProcedureGetTime;External'DATETIME'index2;
ProcedureSetDate;External'DATETIME'index3;
ProcedureGetDate;External'DATETIME'index4;

end;
------------------------------------------------------

programShowTime;{呼叫程式}
usesWinCrt,DateTime;
var
Time:TtimeRec;
begin
GetTime(Time);
WithTimeDo
WriteLn('Timeis',hh,':',mi,':',ss);
end;
-----------------------------------------------------

(6)DDLs之动态使用

programShowTime;
usesWinProcs,WinTypesWinCrt;

type
TTimeRec=Record
ss:integer;
mi:Integer;
hh:Integer;
end;
TGETTime=Procedure(varTime:TTimeRec);
Var
Time:TTimeRec;
Handle:THandle;
GetTime:TGetTime;
Begin
Handle:=LoadLibrary('DATETIME.DLL');
ifHandle>=32then
Begin
@GetTime:=GetProcAddress(Handle,'GETTIME');
If@GetTime<>nilThen{orIfAssigned(GetTime)then}
Begin
GetTime(Time)
WithTimedo
WriteLn('Timeis',hh,':',mi,':',ss);
end;
FreeLibrary(handle);
end;
end.

10.3DDLs之撰写
10.3.1例子
libraryminmax;

functionMin(X,Y:Integer):Integer;
StdCall;
{避免非Delphi之程式呼叫,没有支援register呼叫惯例(内定值)}
Begin
IfX<YThenMin:=X
elseMin:=Y;
end;

functionMax(X,Y:Integer):Integer;StdCall;
Begin
IfX>YThenMax:=X
elseMax:=Y;
end;

exports
Minindex1nameMinResident;
Maxindex2nameMaxResident;
Begin
end.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值