理解 Delphi 的类(二) - 初识类的方法

类包含的内容属性方法事件 
类的主要用途封装继承多态

类的中过程与方法

在Object Pascal语言对类的定义和其他语言一样,都是使用class关键字来声明一个类的。          语法如下:

1 Type 
2     TMyClass = Class
3         private
4             {Private declarations}
5         public
6             {Public declarations}
7         end;

 

上面定义了一个空类,不能实现任何功能,要想是其能够实现功能就必须添加属性和方法

在类中的属性叫做成员变量,方法叫做成员方法;我们在类中定义过程和函数基本相同,唯一的区别就是在类的过程和函数名称前面加上类名和句点。

 1 function TMyClass.MyFun(var x: Integer): Integer;
 2 begin
 3   x := x * 2;
 4   Result := x;
 5 end;
 6 
 7 procedure TMyClass.MyProc(var x: Integer);
 8 begin
 9   x := x * 2;
10 end;

 

 下面把过程与函数包含在一个类里面。

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses                   Winapi.Windows,Winapi.Messages,System.SysUtils,System.Variants,System.Classes,Vcl.Graphics,Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
 6 
 7 type
 8   TForm1 = class(TForm)
 9     Button1: TButton;
10     procedure Button1Click(Sender: TObject);
11   end;
12 
13 var
14   Form1: TForm1;
15 
16 implementation
17 
18 {$R *.dfm}
19 
20 Type
21   TMyClass = class    //定义一个TMyClass类
22     procedure MyProc(var x: Integer);
23     function  MyFun (var x: Integer): Integer;
24   end;
25 {
26   上面定义了一个类, 其中包含了两个方法;
27   函数与过程来到类里面一般叫做方法, 函数是有返回值的方法、过程是没有返回值的方法;
28 
29   在这里, 方法只有定义没有实现;
30   但必须在本单元的 implementation 区内实现.
31 
32 }
33 
34 function TMyClass.MyFun(var x: Integer): Integer;
35 begin
36   x := x * 3;
37   Result := x;
38 end;
39 
40 procedure TMyClass.MyProc(var x: Integer);
41 begin
42   x := x * 3;
43 end;
44 
45 //调用测试
46 procedure TForm1.Button1Click(Sender: TObject);
47 var
48   i: Integer;
49   myClass: TMyClass;          {对象声明}
50 begin
51   myClass := TMyClass.Create; {对象建立}
52 
53   i := 3;
54   myClass.MyProc(i);          {调用方法}
55   ShowMessage(IntToStr(i));   {9}
56 
57   i := 3;
58   i := myClass.MyFun(i);      {调用方法}
59   ShowMessage(IntToStr(i));   {9}
60 
61   myClass.Free;               {对象释放}
62 end;
63 
64 end.

 

一般情况下, 类都会定义在 interface 区; 在 implementation 区定义的类只能本单元使用。

此时我们的类定义就可以放到interface区,直接把定义放在type里面,就无需再多写个type了, 而过程与函数的实现还是放在implementation区

 1 type
 2   TForm1 = class(TForm)
 3     Button1: TButton;
 4     procedure Button1Click(Sender: TObject);
 5   end;
 6 
 7   {类定义, 因为已经在 Type 区了, 可以省略 Type 关键字}
 8   TMyClass = class
 9     procedure MyProc(var x: Integer);
10     function  MyFun (var x: Integer): Integer;
11   end;

 

posted @ 2022-11-02 21:04  终一  阅读(41)  评论(0)    收藏  举报