在 class 中建立 parent/child 关系

Create parent/child relationship in class

我有两个class,一个child class:

type MyChildClass = class
public
parent: ^MyParent;
end;

还有一个parent class:

type MyParentClass = class
public
childs: array of ^MyChildClass;
end;

但是,这不会起作用,因为只有 class 声明最后一个知道另一个。示例:

program Test;

interface

type MyChildClass = class
public
parent: ^MyParentClass;
end;

type MyParentClass = class
public
childs: array of ^MyChildClass;
end;

implementation

end.

这不会编译,因为第 7 行会按预期抛出错误“Undeclared identifier 'MyParentClass'。使用抽象 classes 只能部分解决问题。我真的很难找到解决方案。也许使用界面会有帮助吗?

program Test;

interface
type 
    MyParentClass = class;

    MyChildClass = class
    public
        parent: ^MyParentClass;
    end;

    MyParentClass = class
    public
        childs: array of ^MyChildClass;
    end;

implementation

end.

Pascal 是单通道编译语言,因此编译器只扫描一次单个文件:在每时每刻它都必须知道每个标识符。当您创建循环引用时,就像在这种情况下,您正在引用一个 class 写在 之后 的当前引用,这是不允许的。要解决此问题,您需要使用所谓的 前向声明 ,即您向编译器声明(承诺)它会在代码的某处找到此标识符(查看代码, 问题 1).

此外,您正在定义多个不同的类型范围(通过多次编写 type)。每个类型作用域都有自己的类型(并且在一个作用域中定义的类型不能被另一个作用域看到),因此,您需要定义一个(看代码,problem2) .

program Test;

interface

type // declare a single type scope (problem 2)
    MyParentClass = class; // this is the forward declaration (problem 1)

    MyChildClass = class
    public
        parent: ^MyParentClass;
    end;

    MyParentClass = class
    public
        childs: array of ^MyChildClass;
    end;

implementation

end.