Pascal 在类声明中定义方法体?
我试图用免费的Pascal在类声明中定义类方法,我还没有找到任何在线的例子。目前我必须这样做:Pascal 在类声明中定义方法体?,pascal,lazarus,freepascal,delphi,Pascal,Lazarus,Freepascal,Delphi,我试图用免费的Pascal在类声明中定义类方法,我还没有找到任何在线的例子。目前我必须这样做: unit Characters; {$mode objfpc}{$H+} // Public interface type TCharacter = class(TOBject) private FHealth, FAttack, FDefence: Integer; procedure SetHealth(newValue: Integer); pub
unit Characters;
{$mode objfpc}{$H+}
// Public
interface
type
TCharacter = class(TOBject)
private
FHealth, FAttack, FDefence: Integer;
procedure SetHealth(newValue: Integer);
public
constructor Create(); virtual;
procedure SayShrek();
function GetHealth(): Integer;
published
property Health: Integer read GetHealth write SetHealth;
end;
// Private
implementation
constructor TCharacter.Create;
begin
WriteLn('Ogres have LAYERS!');
end;
procedure TCharacter.SayShrek;
begin
WriteLn('Shrek!');
end;
procedure TCharacter.SetHealth(newValue: Integer);
begin
FHealth:= FHealth + newValue;
end;
function TCharacter.GetHealth() : Integer;
begin
GetHealth:= FHealth;
end;
end.
有没有什么办法可以让这更干净一点?定义其他地方的一切看起来杂乱无章
编辑:
为了澄清这一点,我想做以下几点:
TMyClass = class(TObject)
public
procedure SayHi();
begin
WriteLn('Hello!');
end;
end;
而不必进一步定义它。那可能吗?不,你不能这样做。Pascal有一个单通道编译器,从一开始就是为单通道编译而设计的,所以在声明之前不能使用它 作为伪代码中的一个简单示例:
MyClass = class
procedure MethodA;
begin
MethodB; <== At this point the compiler knows nothing about MethodB
end;
procedure MethodB;
begin
end;
end;
对于课程:
MyClassA = class; // Forward declaration, class will be fully declared later
MyClassB = class
SomeField: MyClassA;
end;
MyClassA = class
AnotherField: MyClassB;
end;
在IDE中,您可以使用Shift+Ctrl+Up/Down键在项的声明和实现之间导航。这在Pascal中是不可能的。它的语法是不允许的 Pascal的基本设计是将单元划分为
接口
(可以做什么?)和实现
(如何做一些事情?)。
编译器在解析实现
部分之前读取所有接口
部分。您可能从C语言中了解到这一点<代码>实现可以描述为*.c文件,而接口
相当于c中的*.h文件
此外,此类代码将严重降低接口
部分(f.i.类声明)的可读性
你希望从中得到什么好处?我希望做更多的事情,比如:MyClassA=类过程测试;开始写入(“测试”);结束;结束;那可能吗?在你的第一个例子中,似乎你确实有方法主体,尽管它引用了一些尚未定义的东西。编译器和过程数各不相同。我认为FPC大约有5-6个通行证。这种方式产生的错误(例如)要好得多。@MarcovandeVoort谢谢。我好像错过了很多年前的一件事:)答案更新了。啊,好的。C的解释帮助很大。非常感谢你的帮助!
MyClassA = class; // Forward declaration, class will be fully declared later
MyClassB = class
SomeField: MyClassA;
end;
MyClassA = class
AnotherField: MyClassB;
end;