Delphi2007新功能-有限的栈对象2009-01-30通过实验,答案是肯定的!这使我感到很兴奋,因为Delphi从诞生之日起,就限定了只能继承于TObject的堆对象,必须通过Create和Free来建立和销毁一个对象,而不能使用栈对象。而栈对象的好处就在于它能和其它类型一样很方便的定义,它能自动调用构造函数和析构函数,在作用域范围内(如函数内的局部对象)不必当心对象的建立和销毁问题。要是Delphi具有了该功能,无意是Delphi编程者们的福音。不过,进一步的测试却比较失望,请看下面的代码:
type
TMyRecord = record
private
x: Integer;
y: Integer;
public
// error: Parameterless constructors not allowed record types
//constructor Create;
// error: A record cannot introduce a destructor
//destructor TMyRecird;
constructor Create(a: Integer);
constructor TMyRecord; overload;
constructor TMyRecord(a, b: Integer); overload;
//constructor TMyRecord(a, b: Integer);
procedure Display;
property xi: Integer read x;
end;
{ TMyRecord }
constructor TMyRecord.Create(a: Integer);
begin
x := a;
y := 0;
end;
procedure TMyRecord.Display;
begin
ShowMessage(Format("x = %d, y = %d", [x, y]));
end;
constructor TMyRecord.TMyRecord;
begin
x := 0;
y := 0;
end;
constructor TMyRecord.TMyRecord(a, b: Integer);
begin
x := a;
y := b;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
rec: TMyRecord;
begin
rec.TMyRecord(100, 200);
rec.Display;
end;