即:Self变量 是该类对应的对象的别名
1
unit Unit1;
2
3
interface
4
5
uses
6
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
7
Dialogs, StdCtrls;
8
type
9
TPig = class(TObject)
10
public
11
pWeight: integer;
12
FUNCTION eat(WeightNow: integer;pFood: Integer): Integer;
13
{ Public declarations }
14
end;
15
type
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
27
var
28
Form1: TForm1;
29
30
implementation {$R *.dfm}
31
32
FUNCTION TPig.eat(WeightNow: integer;pFood: Integer): Integer;
33
VAR
34
wBefore, wNow: Integer;
35
BEGIN
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
);
46
end;
47
//在上面,声明TPig类时,还没有产生该类的对象实体,所以也无法预先知道引用该类的对象
48
//名,但是在TPig.eat这个成员函数实现区,需要访问调用此方法的类对象的数据时,就
49
//可以使用Self来表示该对象的名称,因此,不管TBig类所产生的对象的名称是什么,
50
//都可用Self来访问对象的数据
51
52
53
procedure TForm1.Button1Click(Sender: TObject);
54
VAR
55
Pig1: TPig;
56
TDFood: Integer;
57
begin
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;
64
end;
65
66
procedure TForm1.Button2Click(Sender: TObject);
67
VAR
68
Pig2: TPig;
69
TDFood: Integer;
70
begin
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;
77
end;
78
79
end.
80
81

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81
