Delphi构造函数和析构函数
- 2019-11-16 14:29:00
- 六月
- 来源:
- https://blog.csdn.net/minstrelboy/article/details/23276035
- 转贴 1470
delphi的构造函数的定义是:
constructor create;
delphi的析构函数的定义是:
destructor destroy;
析构函数是不能重载的,但是构造函数是可以重载的。
构造函数在重载的时候要在后面加“overload”,例如:
constructor create;overload;
constructor create(i:integer);overload;
注意,只有两个构造函数以上才叫重载,只有一个就不用“overload;”了。
默认的构造函数是:constructor create; 如果有重载的话,那么默认的构造函数后面也要加overload,正象上面的例子一样。
delphi构造函数在类外定义在什么位置呢?在implementation的后面。下面给出一个实例,可以从这个实例中看出构造函数的定义:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyForm1 = class(TForm1) //自定义一个TMyForm1类
public
constructor Create; overload; //构造函数有重载
constructor Create(I: Integer); overload; //重载一个构造函数
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TMyForm1.Create; //这里定义构造函数
begin
inherited Create(nil); //inherited 表示调用父类的构造函数
end;
constructor TMyForm1.Create(I: Integer);
begin
inherited Create(nil);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
A: TMyForm1;
begin
A := TMyForm1.Create(1);
A.Show;
end;
end.