为什么创建后属性值不保留在对象中?

Joh*_*ony 2 delphi constructor object

我写了这个简单的课:

unit Test;

interface

uses
  SysUtils;

type
  TGram = class
  private
    instanceCreated: boolean;
    constructor Create;
  public
    procedure test;
  end;

implementation

constructor TGram.Create;
begin
  instanceCreated := true;
end;

procedure TGram.test;
begin
  if not instanceCreated
    then raise Exception.Create('The object has not been created.');
end;

end.
Run Code Online (Sandbox Code Playgroud)

当我调用方法测试时,我得到一个例外,那就是它没有被创建。

var test: TGram;
begin
    test := TGram.create;
    test.test;
end
Run Code Online (Sandbox Code Playgroud)

在构造函数中,instanceCreated设置为true(我相信是),但是当我稍后尝试访问它时,它不存在。为什么?如何纠正呢?

Dav*_*nan 8

您被称为TGram.Create您称为的公共构造函数,TObject而不是您的构造函数。那是因为您的构造函数是私有的。使您的构造函数公开,以查看所需的行为。

这很好地展示了编译提示和警告的价值。编译器为您的类发出以下提示:

[dcc32提示]:H2219声明了专用符号“创建”,但从未使用过

您应始终注意提示和警告并适当解决它们。

  • 也缺少在构造函数内部使用“ inherited;”调用继承的构造函数! (3认同)