有沒有辦法在類中使用預定義變數或使用起始值定義它?我的代碼:
TRoom = class(TObject)
private
pos: array[0..2] of integer;
up: TRoom;
right: TRoom;
down: TRoom;
left: TRoom;
--> freeSlots: array[0..3] of string = ('up','right','down','left'); <--
content: string;
end;
uj5u.com熱心網友回復:
有沒有辦法在類中使用預定義變數或使用起始值定義它?
不,您不能為類的實體成員欄位宣告初始值。類默認初始化(即為零)。如果要分配初始值,則應在建構式中進行。
uj5u.com熱心網友回復:
可以宣告一個具有預定義值的常量欄位。如果您以后想更改該值,則有一個技巧。使用編譯器選項“Writable const {$J }”可以改變該值。
TRoom = class(TObject)
private
pos: array[0..2] of integer;
up: TRoom;
right: TRoom;
down: TRoom;
left: TRoom;
content: string;
const
{$J } //Enable writable constants
freeSlot: array[0..3] of string = ('up','right','down','left');
{$J-} //Disable writable constants
end;
var
TR : TRoom;
begin
TR := TRoom.Create;
try
for var i := Low(TR.freeSlot) to High(TR.freeSlot) do
WriteLn(TR.freeSlot[i]);
TR.freeSlot[0] := 'Hello';
for var i := Low(TR.freeSlot) to High(TR.freeSlot) do
WriteLn(TR.freeSlot[i]);
finally
TR.Free;
end;
end;
注意:正如@Andreas 指出的,可寫常量的更改將影響 的所有實體化類TRoom,這可能會限制此技巧的使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363435.html
