Einzelnen Beitrag anzeigen

Blup

Registriert seit: 7. Aug 2008
Ort: Brandenburg
1.429 Beiträge
 
Delphi 10.4 Sydney
 
#12

AW: Zeiger auf eine Klasse

  Alt 12. Aug 2013, 10:15
Ein kleines Beispiel mit Objekten:
Delphi-Quellcode:
type
  TCoord_XY = record //Speichert eine X-Y-Koordinate
    x,y: Double;
  end;

  TPoints = class(TObject)
  private
    FItems: array of array of TCoord_XY;
    function GetItems(x, y: Integer): TCoord_XY;
    procedure SetItems(x, y: Integer; AValue: TCoord_XY);
    function GetSizeX: Integer;
    function GetSizeY: Integer;
  public
    procedure Assign(AValue: TPoints);
    procedure SetSize(x, y: Integer);
    property Items[x, y: Integer]: TCoord_XY read GetItems write SetItems; default;
    property SizeX: Integer read GetSizeX;
    property SizeY: Integer read GetSizeY;
  end;

  TRotor = class(TObject)
  private
    FPoints: TPoints;
  public
    property Points: TPoints read FPoints write FPoints;
  end;

function Coord_XY(x, y: Double): TCoord_XY;

implementation

function Coord_XY(x, y: Double): TCoord_XY;
begin
  Result.x := x;
  Result.y := y;
end;

procedure TPoints.Assign(AValue: TPoints);
begin
  FItems := Copy(AValue.FItems);
end;

function TPoints.GetItems(x, y: Integer): TCoord_XY;
begin
  Result := FItems[x, y];
end;

procedure TPoints.SetItems(x, y: Integer; AValue: TCoord_XY);
begin
  FItems[x, y] := AValue;
end;

function TPoints.GetSizeX: Integer;
begin
  Result := Length(FItems);
end;

function TPoints.GetSizeY: Integer;
begin
  if Length(FItems) > 0 then
    Result := Length(FItems[0])
  else
    Result := 0;
end;

procedure TPoints.SetSize(x, y: Integer);
begin
  SetLength(FItems, x, y);
end;


procedure Test;
var
  Points1, Points2: TPoints;
  Rotor1, Rotor2, Rotor3: TRotor;
begin
  Points1 := nil;
  Points2 := nil;
  Rotor1 := nil;
  Rotor2 := nil;
  Rotor3 := nil;
  try
    {erstes Punkte-Objekt erzeugen}
    Points1 := TPoints.Create;
    Points1.SetSize(1, 1);
    Points1[0, 0] := Coord_XY(1, 0);

    {Rotor mit erstem Punkte-Objekt erzeugen}
    Rotor1 := TRotor.Create;
    Rotor1.Points := Points1;

    {Rotor mit erstem Punkte-Objekt erzeugen}
    Rotor2 := TRotor.Create;
    Rotor2.Points := Points1;

    {zweites Punkte-Objekt erzeugen}
    Points2 := TPoints.Create;
    {bekommt eine Kopie der Punkte des ersten Objekts}
    Points2.Assign(Points1);
    {die Kopie wird verändert}
    Points2.SetSize(3, 1);
    Points2[2, 0] := Coord_XY(3, 0);

    {Rotor mit zweitem Punkte-Objekt erzeugen}
    Rotor3 := TRotor.Create;
    Rotor3.Points := Points2;

    {Points1 und damit Rotor1.Points und Rotor2.Points verändern,
     aber nicht Points2 und Rotor3.Points}

    Points1.SetSize(2, 1);
    Points1[1, 0] := Coord_XY(2, 0);

  finally
    Rotor1.Free;
    Rotor2.Free;
    Rotor3.Free;
    Points1.Free;
    Points2.Free;
  end;
end;
  Mit Zitat antworten Zitat