【问题标题】:Why property value is not kept in object after creation?为什么属性值在创建后不保存在对象中?
【发布时间】:2019-09-11 07:25:26
【问题描述】:

我写了这个简单的类:

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.

当我调用方法 test 时,我得到了它没有被创建的异常。

var test: TGram;
begin
    test := TGram.create;
    test.test;
end

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

【问题讨论】:

  • 你建议如何改变Q?
  • 你确定需要 private 构造函数吗?
  • zed:谢谢!这就是答案!

标签: object delphi constructor


【解决方案1】:

你调用TGram.Create 你调用TObject 的公共构造函数而不是你的构造函数。那是因为您的构造函数是私有的。将您的构造函数公开以查看您想要的行为。

这是对编译提示和警告价值的一个很好的展示。编译器会为你的类发出这个提示:

[dcc32 提示]:H2219 私有符号“创建”已声明但从未使用过

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

【讨论】:

  • 在构造函数中调用带有inherited;的继承构造函数也丢失了!
  • @DelphiCoder 是的。在这种情况下,这并不重要,因为 TObject 构造函数什么都不做。
  • @Delphi Code: 你能发个代码让我看看它应该是什么样子吗?
  • 只不过是在TGram的构造函数中添加了inherited;这个词作为第一行
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多