Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi在表单上使用单元程序_Delphi_Procedure - Fatal编程技术网

Delphi在表单上使用单元程序

Delphi在表单上使用单元程序,delphi,procedure,Delphi,Procedure,我正在学习OOP,到目前为止我已经创建了一个基本程序。我创建了自己的clas: Type Zombie = class private fLife : Integer; fAge : Integer; fHeight: String; public Constructor Create(pLife, pAge : Integer; pHeight : String); Procedure SetLife(pLife : Integer); functi

我正在学习OOP,到目前为止我已经创建了一个基本程序。我创建了自己的clas:

Type
Zombie = class
  private
   fLife : Integer;
   fAge : Integer;
   fHeight: String;
  public
   Constructor Create(pLife, pAge : Integer; pHeight : String);
   Procedure SetLife(pLife : Integer);
   function GetLife : Integer;
   Procedure ShowLife;
end;
ShowLife的程序完全按照它所说的做:

procedure Zombie.ShowLife;
begin
ShowMessage(inttostr(fLife));
end;
我试图在表单上调用此过程,但它显示未声明的标识符:

procedure Tform1.ShowLifebtnClick(Sender: TObject);
begin
Zombies_Unit.ShowLife;
end;

我已将该单元包含在表单的用户中。如何在另一个窗体上使用方法

您必须创建类的实例并像

MyZombie := Zombie.create(20,15);
MyZombie.ShowLife;
...
MyZombie.free;
从手机发送,无法格式化代码

编辑/补充:

由于我的简短回答似乎适用于技术不良习惯(对此我很抱歉),我想向提问者补充以下建议:


请使用Try/Finally构造,以避免在create()和free()之间发生错误时对象不会被删除,就像Zdravko Danev的回答所指出的那样。使用通用命名约定使代码更易于理解(例如,TZombie作为类名)也是有意义的。

您需要在使用之前/之后创建并释放对象。模式如下:

MyZombie := TZombie.Create(10, 20, 30); 
try
  MyZombie.ShowLife(); 
finally
  MyZombie.Free();
end;

你必须注意一件事:你的班级和你的表格在同一个文件中?如果答案为否,则必须在表单文件的
uses
上声明单元名称,如:

unit MyUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TMyForm = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MyForm: TMyForm;

implementation

uses unitzombie; //The name unit where is your class

{$R *.dfm}

end.
解决此小问题后,必须先创建对象,然后再调用此方法:

procedure Tform1.ShowLifebtnClick(Sender: TObject);
var 
   Zombi: Zombie; 
begin
      Zombi := Zombie.Create(5,10,15);
   try
      Zombi.ShowLife;
   finally
      Zombi.Free;
   end;
end;

你错过了最后一次尝试正确,我想这是一个初学者的问题,我想让他在使用物体时找到正确的方向。@MichaSchumann我想你错过了重点。你展示了糟糕的资源保护;i、 e.你指向了完全错误的方向。如果这真的是重点,我最好不要再回答任何问题,因为这些答案总是缺少一些非常重要的模式。很多时候,你会创建一个对象,并且只在以后不再需要时才释放它。出于测试/学习目的,通常会将变量声明为Form类的成员,然后在OnCreate事件处理程序中创建对象,并在OnDestroy事件处理程序中销毁它(无调用)。这样,您就可以在窗体的生存期内测试对象。您需要在类型为
Zombie
的对象(即类实例)上调用方法
ShowLife
,而不是在单元上。该单元只是定义了类
Zombie
的文件。@ZdravkoDanev的答案说明了如何做到这一点。单元也可以定义所谓的全局函数,但它们不是类的方法,比如
Zombie