【问题标题】:Pascal - Class inheritance between two different files?Pascal - 两个不同文件之间的类继承?
【发布时间】:2015-08-24 03:57:55
【问题描述】:

假设我有两个文件,characters.pasogre.pas。食人魔是一个角色,但为了清洁起见,我试图将这两个文件分开。在characters.pas我有

unit Characters;

{$mode objfpc}{$H+}

interface
type
  TCharacter = class(TOBject)
    private
      // ...
    public
      // ...
    published
      // ...
  end;

implementation
  // Method bodies
end.

ogre.pas我有

unit Ogre;

{$mode objfpc}{$H+}

interface
type
  TOgre = class(TCharacter)
    public
        constructor create; override;
    end;


implementation

constructor TOgre.create();
begin
  // Banana banana banana
end;
end.

在任一 .pas 文件中的任意位置添加 uses 块会引发错误,这使我相信所有依赖继承的类都必须与其父类位于同一文件中。我错过了什么吗?

【问题讨论】:

  • 在任一 .pas 文件中的任意位置添加 uses 块都会引发错误 很高兴看到这些代码和错误详细信息。但是@Nestedtype 已经回答了你的问题。

标签: pascal lazarus freepascal delphi


【解决方案1】:

是的,你错过了一些东西:use 部分。你必须声明unit Ogre 使用unit Characters

单位食人魔;

{$mode objfpc}{$H+}

interface

uses
  Characters;

type
  TOgre = class(TCharacter)
    public
        constructor create; override;
    end;


implementation

constructor TOgre.create();
begin
  // Banana banana banana
end;
end. 

阅读更多:

另请注意,如果您希望某些字段从 TCharacterTOgre 可见但仍无法从主程序访问,则必须将其可见性设置为 protected

【讨论】:

  • 由于某种奇怪的原因,uses 字段开始工作,尽管以前它会导致编译器抛出错误。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多