当创建一个继承自另一个类的类时,在创建派生类时,是否应该调用基类的构造函数?
Type
TBase = Class
constructor xMain;
End;
TDerived = Class(TBase)
constructor xMain;
End;
constructor TBase.xMain;
begin
MessageBox(0,'TBase','TBase',0);
end;
constructor TDerived.xMain;
begin
MessageBox(0,'TDerived','TDerived',0);
end;
Var
xTClass:TDerived;
begin
xTClass := TDerived.xMain;
end.
我认为这会导致MessageBox显示“TBase”然后“TDerived”。但事实并非如此。当运行上面的代码时,它只会导致一个MessageBox显示“TDerived”。
答案 0 :(得分:9)
constructor TDerived.xMain;
begin
inherited;
MessageBox(0,'TDerived','TDerived',0);
end;
答案 1 :(得分:6)
在TDerived.xMain中添加继承;否则将不会调用祖先的代码;
begin
inherited;//call the ancestor TBase.xMain
MessageBox(0,'TDerived','TDerived',0);
end;
此问题也可以帮助您理解继承的保留字:
Delphi: How to call inherited inherited ancestor on a virtual method?
另一个好的资源是http://www.delphibasics.co.uk/RTL.asp?Name=Inherited