转载至:两种类的声明方法
说明:
Delphi的类声明有两种方法,一种是继承了Delphi的内建类的声明,另一种则是完全自定义的类声明。
这两种类的区别不仅在于声明程序的不同,还会影响到对象实体的内存管理。
1unit Unit1;
2
3interface
4
5uses
6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
7 Dialogs, StdCtrls, Buttons;
8
9type
10 TForm1 = class(TForm)
11 btn1: TBitBtn;
12 btn2: TBitBtn;
13 procedure btn1Click(Sender: TObject);
14 procedure btn2Click(Sender: TObject);
15 private
16 { Private declarations }
17 public
18 { Public declarations }
19 end;
20
21 TMyCalss1 = class //声明一个继承Delphi内建类的Class类,//默认继承自 TOBJECT
22 public
23 value1:Integer;
24 string1:string;
25 end;
26
27 TMyClass2 = object //声明一个完全自定义的Object类
28 public
29 value1:Integer;
30 string1:string;
31 end;
32
33var
34 Form1: TForm1;
35
36implementation
37
38{$R *.dfm}
39
40procedure TForm1.btn1Click(Sender: TObject);
41var
42 TTest1:TMyCalss1;
43begin
44 TTest1 := TMyCalss1.Create; //必须使用其父类的构造方法
45
46 TTest1.value1 := 12;
47 TTest1.string1:= '您好';
48 ShowMessage(IntToStr(TTest1.value1) + #13 + TTest1.string1);
49
50 TTest1.Free; //必须使用其父类的析构方法
51
52end;
53
54
55
56procedure TForm1.btn2Click(Sender: TObject);
57var
58 TTest2:TMyClass2;
59begin
60
61 TTest2.value1 := 34; //不必使用Create的构造方法,可以直接构造该对象的实体,并且操作该对象的成员
62 TTest2.string1 := '我好';
63 ShowMessage(IntToStr(TTest2.value1) + #13 + TTest2.string1);
64
65end;
66
67end.
2
3interface
4
5uses
6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
7 Dialogs, StdCtrls, Buttons;
8
9type
10 TForm1 = class(TForm)
11 btn1: TBitBtn;
12 btn2: TBitBtn;
13 procedure btn1Click(Sender: TObject);
14 procedure btn2Click(Sender: TObject);
15 private
16 { Private declarations }
17 public
18 { Public declarations }
19 end;
20
21 TMyCalss1 = class //声明一个继承Delphi内建类的Class类,//默认继承自 TOBJECT
22 public
23 value1:Integer;
24 string1:string;
25 end;
26
27 TMyClass2 = object //声明一个完全自定义的Object类
28 public
29 value1:Integer;
30 string1:string;
31 end;
32
33var
34 Form1: TForm1;
35
36implementation
37
38{$R *.dfm}
39
40procedure TForm1.btn1Click(Sender: TObject);
41var
42 TTest1:TMyCalss1;
43begin
44 TTest1 := TMyCalss1.Create; //必须使用其父类的构造方法
45
46 TTest1.value1 := 12;
47 TTest1.string1:= '您好';
48 ShowMessage(IntToStr(TTest1.value1) + #13 + TTest1.string1);
49
50 TTest1.Free; //必须使用其父类的析构方法
51
52end;
53
54
55
56procedure TForm1.btn2Click(Sender: TObject);
57var
58 TTest2:TMyClass2;
59begin
60
61 TTest2.value1 := 34; //不必使用Create的构造方法,可以直接构造该对象的实体,并且操作该对象的成员
62 TTest2.string1 := '我好';
63 ShowMessage(IntToStr(TTest2.value1) + #13 + TTest2.string1);
64
65end;
66
67end.