Delphi 继承嵌套类是否可行?
我有一个父类,它在“protected”选项卡中声明了一个嵌套类,并带有一个protected class变量。在另一个单元中,我有一个从父类继承的子类。当我尝试从父类访问受保护/公共的对象时,它会起作用,但当我尝试访问受嵌套类保护的对象时,它不起作用Delphi 继承嵌套类是否可行?,delphi,oop,class,Delphi,Oop,Class,我有一个父类,它在“protected”选项卡中声明了一个嵌套类,并带有一个protected class变量。在另一个单元中,我有一个从父类继承的子类。当我尝试从父类访问受保护/公共的对象时,它会起作用,但当我尝试访问受嵌套类保护的对象时,它不起作用 type TParent = class(TObject) protected class var x:integer; type TNested = class(TObject) prot
type
TParent = class(TObject)
protected
class var x:integer;
type
TNested = class(TObject)
protected
class var y:integer;
end;
end;
我在子类中的代码:
x := 10; //works
y := 10; //undeclarated idenitifier 'y'.
TNested.y := 10; //undeclarated idenitifier 'y'
子类的声明为:
type
TChild = class(TParent);
如何访问y?y:integer是TNested类的受保护字段,即只能由TNested及其自身继承的类使用。
您可能会从TParent使用TNested,但这是因为在Delphi中,如果从同一个单元调用,您可能会有更大的访问权限。因此TParent和TNested在同一个单元中,因此您可以从TParent调用TNested protected data。但是,由于TChild与TNested位于不同的单元中,这是不可能的。如果TChild和TParent位于同一单元中,这将实际起作用,因为单元中的类之间存在着隐含的友谊 要访问示例中的y,您需要执行以下两项操作之一:
您给出的示例是使用嵌套类,而不是继承它 嵌套类可以在声明类的子类中继承:
TSubParent = class(TParent)
protected
type
TSubNested = class(TNested)
public
class var Z : integer;
end;
end;
不是这里所问的。TNested是一个嵌套类(在D2006?之后提供),而不是同一单元中的另一个类。它被称为TParent。TNested@Gerry,这里的问题是从类外部调用某个类的受保护元素。无论该类驻留在何处,从外部访问某个类的受保护字段在某种程度上违反了封装。
TSubParent = class(TParent)
protected
type
TSubNested = class(TNested)
public
class var Z : integer;
end;
end;