delphi7中类的定义和使用
9595 点击·0 回帖
![]() | ![]() | |
![]() | 类成员类型有待考究。望知者相告。
在delphi7中怎么创建一个自己的类: 1、类定义位置:新建一个单元,如下所示 [delphi] unit Unit3; interface implementation end. unit Unit3; interface implementation end. 类的定义应在interface和implementation之间。类的实现部分在implementation和end.之间。以type始以end;止。 2、类成员类型:public、private、published默认类型为public 3、构造函数、析构函数、重载函数。 构造函数和析构函数必须是固定格式。重载函数通过在函数定义后加overload;实现。 4、类成员数据和成员方法的位置关系:在成员类型关键字之后必须是先成员数据后成员方法,否则会报错:Field definition not allowed after methods or properties. 5、类的使用:声明一个类对象后,必须先调用其create方法,之后才可使用该类对象。 6、free是TObject类的方法,never call destroy directly,而是调用free method。 有两个比较nb的事: 1)仅有成员函数声明没有成员函数实现会报错。 2)delphi的initialization和finalization单元,可代替构筑函数和析构函数。 类定义和使用示例 [delphi] unit Unit2; interface //有基类时 type TStudent = class(基类) type TStudent=class procedure SetID(ID:string); public ID : string; function GetID:string; constructor Create(i:integer); overload; constructor Create ; overload; destructor Destroy; end; implementation procedure TStudent.SetID(ID:string); begin end; function TStudent.GetID:string; begin result := ID; end; constructor TStudent.Create(i:integer); begin ID := 'abc'; end; constructor TStudent.Create; begin end; destructor TStudent.Destroy; begin end; end. unit Unit2; interface //有基类时 type TStudent = class(基类) type TStudent=class procedure SetID(ID:string); public ID : string; function GetID:string; constructor Create(i:integer); overload; constructor Create ; overload; destructor Destroy; end; implementation procedure TStudent.SetID(ID:string); begin end; function TStudent.GetID:string; begin result := ID; end; constructor TStudent.Create(i:integer); begin ID := 'abc'; end; constructor TStudent.Create; begin end; destructor TStudent.Destroy; begin end; end. [delphi] procedure TForm1.Button1Click(Sender: TObject); var stuA : TStudent; begin stuA := TStudent.Create(1); ShowMessage(stuA.GetID); end; | |
![]() | ![]() |