【发布时间】:2017-08-08 11:41:52
【问题描述】:
我知道这是一个令人费解的问题,我相信有人可以将其简化为基本问题。
考虑以下代码:
TTestClass = class
public
end;
TTestClassDescendant = class(TTestClass)
public
constructor Create;
end;
implementation
procedure TForm1.Button1Click(Sender: TObject);
var tc: TTestClass;
begin
tc := TTestClassDescendant.Create;
tc.Free;
end;
{ TTestClassDescendant }
constructor TTestClassDescendant.Create;
begin
ShowMessage('Create executed') // this gets executed
end;
Create 过程被正确执行。
现在考虑以下代码:
TTestClass = class
public
end;
TTestClassDescendant = class(TTestClass)
public
constructor Create;
end;
TTestClassClass = class of TTestClass;
implementation
procedure TForm1.Button1Click(Sender: TObject);
var tc: TTestClass;
tcc: TTestClassClass;
begin
tcc := TTestClassDescendant;
tc := tcc.Create;
tc.Free
end;
{ TTestClassDescendant }
constructor TTestClassDescendant.Create;
begin
ShowMessage('Create executed') // this does NOT get executed
end;
后代类的 Create 过程不再执行。
但是,如果我在父类中引入构造函数并在后代类中覆盖它,它确实会被执行:
TTestClass = class
public
constructor Create; virtual;
end;
TTestClassDescendant = class(TTestClass)
public
constructor Create; override;
end;
如果我忽略了显而易见的事情,请原谅我,但不应该在通过类变量进行构造时执行第二个代码块中的构造函数代码,就像通过类标识符本身调用它时一样?
【问题讨论】:
标签: class delphi constructor delphi-xe2