【发布时间】:2009-07-20 18:33:21
【问题描述】:
子类可以访问父类的protected函数,但是父类不能访问子类的protected函数。
我想尽可能保持两个类的私有。父类是一个表单,并且只使用一次实例。子类中的所有函数都是静态的,它继承自父类。
如何从父类访问子类(在另一个单元)中的非公共静态方法?
编辑:
父类(第一单元):
interface
type
TParent = class
public
procedure Initialize;
protected
procedure Test; virtual;
end;
implementation
procedure TParent.Initialize;
begin
Writeln('Initializing');
Test;
end;
procedure TParent.Test;
begin
end;
儿童班(第二单元):
interface
uses
ParentClass;
type
TChild = class(TParent)
protected
procedure Test;override;
end;
implementation
procedure TChild.Test;
begin
Writeln('Test!');
end;
代码(第三单元):
var c:TParent;
begin
try
c := c.Create;
c.Initialize;
c.Free;
Readln;
end;
输出只是“初始化”。我尝试调试它,它没有到达子类。
【问题讨论】:
-
它永远不会到达子类,因为您创建错误的类。将您的创建更改为 C := TChild.Create ,它将起作用。
-
您错误地实例化了该类。我想你之前已经被告知过。当您调用
c.Create时,编译器没有警告您吗?如果要创建TChild的实例,则需要在该类上调用构造函数:TChild.Create。
标签: delphi oop inheritance class