Self的含义及举例

Self变量,Self是一个内建变量,是在类方法实现区使用时,参考到该类方法对应的对象实体
 即:Self变量 是该类对应的对象的别名
 1unit Unit1;
 2
 3interface
 4
 5uses
 6  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 7  Dialogs, StdCtrls;
 8type
 9  TPig = class(TObject)
10  public
11    pWeight: integer;
12    FUNCTION eat(WeightNow: integer;pFood: Integer): Integer;
13    { Public declarations }
14  end;
15type
16  TForm1 = class(TForm)
17    Button1: TButton;
18    Button2: TButton;
19    procedure Button1Click(Sender: TObject);
20    procedure Button2Click(Sender: TObject);
21  private
22    { Private declarations }
23  public
24    { Public declarations }
25  end;
26
27var
28  Form1: TForm1;
29
30implementation    {$R *.dfm}
31
32FUNCTION TPig.eat(WeightNow: integer;pFood: Integer): Integer;
33 VAR
34   wBefore, wNow: Integer;
35BEGIN
36 self.pWeight := WeightNow; //每次对象引用时,Self即代表对象名
37 //  pWeight := WeightNow; // 也是可以的
38  wBefore := self.pWeight;
39  self.pWeight := self.pWeight + (pFood div 6);
40  wNow := self.pWeight;
41  result := wNow - wBefore;
42  ShowMessage('原本重' + IntToStr(wBefore) + '公斤' + #13 +
43              '现在重' + IntToStr(wNow) + '公斤' + #13 +
44              '总共重了' + IntToStr(result) + '公斤'
45              );
46end;
47//在上面,声明TPig类时,还没有产生该类的对象实体,所以也无法预先知道引用该类的对象
48//名,但是在TPig.eat这个成员函数实现区,需要访问调用此方法的类对象的数据时,就
49//可以使用Self来表示该对象的名称,因此,不管TBig类所产生的对象的名称是什么,
50//都可用Self来访问对象的数据
51
52
53procedure TForm1.Button1Click(Sender: TObject);
54VAR
55  Pig1: TPig;
56  TDFood: Integer;
57begin
58  Pig1 := TPig.Create;
59  Pig1.eat(61,13) ;
60  ShowMessage('现在Pig1的重量是: ' + IntToStr(Pig1.pWeight) + '公斤');
61  TDFood := StrToInt(InputBox('今天要喂多少?','输入公斤数(整数)','11'));
62  Pig1.eat(Pig1.pWeight,TDFood);
63  Pig1.Free;
64end;
65
66procedure TForm1.Button2Click(Sender: TObject);
67VAR
68  Pig2: TPig;
69  TDFood: Integer;
70begin
71  Pig2 := TPig.Create;
72  Pig2.eat(61,13) ;
73  ShowMessage('现在Pig2的重量是: ' + IntToStr(Pig2.pWeight) + '公斤');
74  TDFood := StrToInt(InputBox('今天要喂多少?','输入公斤数(整数)','11'));
75  Pig2.eat(Pig2.pWeight,TDFood);
76  Pig2.Free;
77end;
78
79end
80
81
原文地址:https://www.cnblogs.com/dreamszx/p/1572021.html