typestar

Constructores y Free en Delphi

Una reserva construida por un constructor con argumentos y liberada después en un bloque finally.

program ConstructorFree;
uses SysUtils;
type
  TBooking = class
    Summary: string;
    constructor Create(const AGuest: string; ANights: Integer);
  end;
constructor TBooking.Create(const AGuest: string; ANights: Integer);
begin
  Summary := Format('%s: %d nights', [AGuest, ANights]);
end;
var Stay: TBooking;
begin
  Stay := TBooking.Create('Rivera', 3);  // whoever calls Create owns it
  try
    WriteLn(Stay.Summary);
  finally
    Stay.Free;  // and the owner frees it, on every way out of the block
  end;
end.

Cómo funciona

  1. constructor Create(const AGuest: string; ANights: Integer) toma los valores que necesita el objeto.
  2. El cuerpo llena el campo con Format('%s: %d nights', [AGuest, ANights]).
  3. Stay := TBooking.Create('Rivera', 3) deja al llamador como dueño, así que Stay.Free va en finally.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
489
Tokens
101
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 87 segundos.

Escribe este fragmento

Paso 3 de 3 en Clases; paso 21 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →