初始化时需要setLength一个动态数组吗? [英] Do I need to setLength a dynamic array on initialization?
问题描述
type Tmyclass = class(TObject)
somearray: array of TSometype
FBool: Boolean;
Fint: Integer;
Fstr: string;
constructor Create;
destructor Destroy; override;
end;
implementation
constructor Tmyclass.Create;
begin
inherited;
SetLength(somearray,0); //is this needed?
end;
destructor TmyClass.Destroy;
begin
SetLength(somearray,0); //this IS needed!
inherited;
end;
还有什么类型在创建时初始化?例如我在课堂上宣布的。
是FBool guranteed是假的?
是FInt guranteed为0?
是Fstr guranteed要'?
Also what types are initialized on creation? For example what I declared in the class. is FBool guranteed to be false? is FInt guranteed to be 0? is Fstr guranteed to be ''?
当地的?只有字符串?
我使用Delphi XE。
I use Delphi XE.
推荐答案
属性对象的内存在对象构造(堆分配)上初始化为0,因此通常您不需要初始化属于类的任何属性,默认值(零内存)为:
All the memory belonging to objects are initialized to 0 on object construction (heap allocation), so usually you don't need to initialize anything belonging to a class, default values (zero memory) are:
- 字符串将为''
- 整数将为0
- 浮点变量将为0
-
- boolean将为false
- 指针和对象引用将为零
- 动态数组将包含零个元素。 / li>
- strings will be ''
- integers will be 0
- floating point variables will be 0
- boolean will be false
- pointers and object references will be nil
- dynamic arrays will contain zero elements.
等等。
对于本地变量和与堆栈相关的任何内容,它将包含垃圾,因此在使用变量之前,您有责任提供有意义的值。
For local variables and anything related to stack, it will contain garbage, so you're responsible to provide a meaningful value before using the variables.
如下所示:
procedure Something;
var
x: Integer;
begin
ShowMessage(IntToStr(X));
end;
将显示一个随机值。
这篇关于初始化时需要setLength一个动态数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!