假设我有以下(示例)类:
TMyClass1 = class(TThread)
constructor Create(CreateSuspended: Boolean);
end;
TMyClass2 = class(TMyClass1)
constructor Create(CreateSuspended: Boolean);
end;
代码:
constructor TMyClass1.Create(CreateSuspended: Boolean);
begin
inherited;
end;
constructor TMyClass2.Create(CreateSuspended: Boolean);
begin
inherited;
end;
如何防止TMyClass2.Create不调用TMyClass1的构造函数,但是仍然正确创建了类?
在实际代码中,TMyClass1的创建做了一些不应该在TMyClass2.create中发生的事情。 TMyClass1有很多功能和程序,我不想为TMyClass2复制。
答案 0 :(得分:-3)
有很多方法可以做到这一点。例如,您可以使用多个构造函数:
TMyClass1 = class(TThread)
protected
constructor CreateInternal(CreateSuspended: boolean);
public
constructor Create(CreateSuspended: boolean);
end;
....
constructor TMyClass1.Create(CreateSuspended: boolean);
begin
CreateInternal(CreateSuspended);
... do other things which shouldn't be in Class2 ...
end;
constructor TMyClass2.Create(CreateSuspended: boolean);
begin
inherited CreateInternal(CreateSuspended);
...
end;
但通常它看起来像设计错误。也许你应该制作TMyClass0 = class(TThread),TMyClass1 = class(TMyClass0),TMyClass2 = class(TMyClass0),也许是其他,但你的描述是可疑的。