【问题标题】:Create parent/child relationship in class在课堂上创建父/子关系
【发布时间】:2018-08-26 17:18:35
【问题描述】:

我有两个类,一个子类:

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

还有一个父类:

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

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

program Test;

interface

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

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

implementation

end.

这不会编译,因为第 7 行将抛出错误“未声明的标识符 'MyParentClass' 符合预期。使用抽象类只能部分解决问题。我真的很难找到解决方案。也许使用接口会有所帮助?

【问题讨论】:

  • Forward declaration 是您所缺少的。除此之外,您可以声明那些不像指针的字段类型(通过删除那些 ^ 运算符)。我们使用 T 前缀作为 Type 声明。
  • 非常感谢!就是这样!
  • 不客气!
  • FWIW,不要对父级或子级使用指针语法。在 Delphi 中,类实例变量已经是引用。在我关于指针(和引用)的文章中了解更多信息:Addressing pointers -- References
  • @David:我的意思是在这种情况下,因此提到了父母和孩子。所以我认为我写的是正确的。

标签: oop pascal paradigms delphi


【解决方案1】:

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

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

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.

【讨论】:

    【解决方案2】:
    program Test;
    
    interface
    type 
        MyParentClass = class;
    
        MyChildClass = class
        public
            parent: ^MyParentClass;
        end;
    
        MyParentClass = class
        public
            childs: array of ^MyChildClass;
        end;
    
    implementation
    
    end.
    

    【讨论】:

    • 如果你解释了你实际做了什么,我会投票赞成这个答案。
    • 正如@Jerry 已经说过的,请解释为什么您的代码“有效”,即您为什么要这样做。那么这将是一个很好的答案。仅仅发布代码是不够的。您可以编辑您的答案并添加一些解释。
    • 你选择不解释你的答案真是太可惜了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    相关资源
    最近更新 更多