Object 为什么属性值在创建后不保留在对象中?
我写了这个简单的类:Object 为什么属性值在创建后不保留在对象中?,object,delphi,constructor,Object,Delphi,Constructor,我写了这个简单的类: unit Test; interface uses SysUtils; type TGram = class private instanceCreated: boolean; constructor Create; public procedure test; end; implementation constructor TGram.Create; begin instanceCreated := true; e
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.
当我调用方法测试时,我得到一个异常,它没有被创建
var test: TGram;
begin
test := TGram.create;
test.test;
end
在构造函数中,instanceCreated被设置为true(我相信是这样),但当我稍后尝试访问它时,它不在那里。为什么?如何更正此问题?您正在调用
TGram。创建您调用的是TObject
的公共构造函数,而不是您的构造函数。这是因为你的构造函数是私有的。让你成为公众,看看你想要的行为
这是编译提示和警告的价值的极好演示。编译器为您的类发出以下提示:
[dcc32提示]:H2219已声明但从未使用的专用符号“创建”
您应该始终注意提示和警告,并适当解决它们。您建议如何更改Q?您确定需要私人构造函数吗?zed:谢谢!这就是答案!使用inherited调用继承的构造函数构造函数中的代码>也丢失了@这是真的。在这种情况下,这并不重要,因为TObject
constrcutor什么都不做。@Delphi-code:你能发送一个代码让我看看它应该是什么样子吗?它不仅仅是添加单词inherited
作为TGram的构造函数内的第一行