为何创建对像时不会调用构造函数?该如何解决
为何创建对像时不会调用构造函数?
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,Unit2;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
a:ta;
begin
a:=ta.Create;
a.Free;
end;
end.
==========================
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes;
type
ta=class(tobject)
private
constructor create;overload;
destructor destroy;override;
end;
implementation
{ ta }
constructor ta.create;
begin
inherited;
messagebox(0, 'a', 'a', 0);
end;
destructor ta.destroy;
begin
messagebox(0, 'b', 'b', 0);
inherited;
end;
end.
==================
这是全部代码,为何在按按钮时,不会调用构造函数呢?
------解决方案--------------------
ta=class(tobject)
private ->改成public
------解决方案--------------------
不要把constructor create;overload; destructor destroy;override; 写在Private段里
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,Unit2;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
a:ta;
begin
a:=ta.Create;
a.Free;
end;
end.
==========================
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes;
type
ta=class(tobject)
private
constructor create;overload;
destructor destroy;override;
end;
implementation
{ ta }
constructor ta.create;
begin
inherited;
messagebox(0, 'a', 'a', 0);
end;
destructor ta.destroy;
begin
messagebox(0, 'b', 'b', 0);
inherited;
end;
end.
==================
这是全部代码,为何在按按钮时,不会调用构造函数呢?
------解决方案--------------------
ta=class(tobject)
private ->改成public
------解决方案--------------------
不要把constructor create;overload; destructor destroy;override; 写在Private段里