Class 使用类引用的多态性和继承?
下面控制台应用程序的输出是Class 使用类引用的多态性和继承?,class,delphi,reference,Class,Delphi,Reference,下面控制台应用程序的输出是 Parent Parent Parent 而不是 Parent Child1 Child2 为什么会发生这种情况?此外,如何获得预期的输出?非常感谢 PS:读了这篇文章后仍然没有任何线索 您的代码的行为方式是这样的,因为您的构造函数不是虚拟的。这意味着编译器在编译时绑定到它们。因此,这意味着无法考虑运行时类型,代码总是调用TParent.Create 为了允许程序使用运行时类型绑定,您需要使用虚拟方法和多态性。因此,您可以使用虚拟构造函数来解决问题: progra
Parent
Parent
Parent
而不是
Parent
Child1
Child2
为什么会发生这种情况?此外,如何获得预期的输出?非常感谢
PS:读了这篇文章后仍然没有任何线索
您的代码的行为方式是这样的,因为您的构造函数不是虚拟的。这意味着编译器在编译时绑定到它们。因此,这意味着无法考虑运行时类型,代码总是调用
TParent.Create
为了允许程序使用运行时类型绑定,您需要使用虚拟方法和多态性。因此,您可以使用虚拟构造函数来解决问题:
program Project1;
{$APPTYPE CONSOLE}
type
TParent = class;
TParentClass = class of TParent;
TParent = class
public
ID: string;
constructor Create; virtual;
end;
TChild1 = class(TParent)
public
constructor Create; override;
end;
TChild2 = class(TParent)
public
constructor Create; override;
end;
constructor TParent.Create;
begin
ID := 'Parent';
end;
constructor TChild1.Create;
begin
ID := 'Child1';
end;
constructor TChild2.Create;
begin
ID := 'Child2';
end;
procedure Test(ImplClass: TParentClass);
var
ImplInstance: TParent;
begin
ImplInstance := ImplClass.Create;
WriteLn(ImplInstance.ID);
ImplInstance.Free;
end;
begin
Test(TParent);
Test(TChild1);
Test(TChild2);
Readln;
end.
输出
Parent
Child1
Child2
父母亲
孩子1
孩子2
这里的一条经验法则是,无论何时使用元类实例化对象,类构造函数都应该是虚拟的。这条经验法则也有例外,但我个人从未在我的产品代码中违反过这条规则。注意,我编辑了代码。您无意在每个派生类中添加新的
ID
字段,这些派生类隐藏在TParent
中声明的字段。感谢您的提示和帮助!你能帮我解释一下这个经验法则吗?当构造函数没有“显式使用”时,它们是否需要是虚拟的?
Parent
Child1
Child2