Форум по Delphi программированию

Delphi Sources



Вернуться   Форум по Delphi программированию > Все о Delphi > [ "Начинающим" ]
Ник
Пароль
Регистрация <<         Правила форума         >> FAQ Пользователи Календарь Поиск Сообщения за сегодня Все разделы прочитаны

Ответ
 
Опции темы Поиск в этой теме Опции просмотра
  #1  
Старый 02.06.2010, 18:41
DungeonLords DungeonLords вне форума
Активный
 
Регистрация: 21.07.2008
Сообщения: 257
Репутация: 14
Вопрос Как дублировать процедуру и поля? [ООП]

Привет всем! Возник вопрос касательно ООП.

Есть несколько классов:
Код:
TInteger3Locations = class
Location : array of Integer;
Value: array of TVector3i; 
Name:array of ^string;
procedure SetLengthFor(NewLength:Integer);
end;

TInteger4Locations = class
Location : array of Integer;
Value: array of TVector4i; 
Name:array of ^string;
procedure SetLengthFor(NewLength:Integer);
end;

TFloat1fLocations = class
Location : array of Integer;
Value: array of Single;
Name:array of ^string;
procedure SetLengthFor(NewLength:Integer);
end;

Как вы можете видеть, тут у каждого класса дублируется поле Location. Я решил проблему тем, что создал предка для этих классов и вынес Location и Name туда. Это просто и проблема не в этом.
Код:
TBaseLocations = class
Location : array of glint;
Name:array of ^string;
end;

Проблема в том, что помимо полей у этих классов дублируется ещё и процедура SetLengthFor. Вот её код:
Код:
procedure TInteger3Locations.SetLengthFor(NewLength:Integer);
var i:Integer;
begin
SetLength(Location,NewLength);
SetLength(Value,NewLength);
SetLength(Name,NewLength);
for i:=0 to NewLength-1 do begin
New(Value[i]);
New(Name[i]);
end;
end;
Как мне перенести её в класс-предок? Или как вообще назначить одну такую процедуру всем классам? Ведь у класса-предка нет поля Value. Создавать абсолютно одинаковые процедуры для трёх (в реале больше) классов - глопость, я уверен.
__________________
Делаем'c разные игры. Искать на glscene.ru
Ответить с цитированием
  #2  
Старый 03.06.2010, 04:28
Kapitoshka438 Kapitoshka438 вне форума
Начинающий
 
Регистрация: 09.11.2009
Сообщения: 145
Репутация: 238
По умолчанию

Код:
unit Unit1;

interface

type
  TPoint = class
  end;

  TVector3i = class(TPoint)
    X1, X2, X3: Single;
  end;

  TVector4i = class(TPoint)
    X1, X2, X3, X4: Single;
  end;

  TSingle = class(TPoint)
    X1: Single;
  end;

  TBaseLocations = class
    Location : array of Integer;
    Name: array of ^string;
    Value: array of TPoint;
    procedure SetLengthFor(NewLength: Integer);
    procedure AddValue(Index: Integer); virtual; abstract;
    destructor Destroy; override;
  end;

  TInteger3Locations = class(TBaseLocations)
    procedure AddValue(Index: Integer); override;
  end;

  TInteger4Locations = class(TBaseLocations)
    procedure AddValue(Index: Integer); override;
  end;

  TFloat1fLocations = class(TBaseLocations)
    procedure AddValue(Index: Integer); override;
  end;

implementation

{ TBaseLocations }

destructor TBaseLocations.Destroy;
var
  I: Integer;
begin
  for I := Low(Value) to High(Value) do
    Value[i].Free;
  inherited;
end;

procedure TBaseLocations.SetLengthFor(NewLength: Integer);
var
  I: Integer;
begin
  SetLength(Location, NewLength);
  SetLength(Name, NewLength);
  SetLength(Value, NewLength);
  for I := 0 to NewLength - 1 do begin
    AddValue(I);
    New(Name[i]);
  end;
end;

{ TInteger3Locations }

procedure TInteger3Locations.AddValue(Index: Integer);
begin
  Value[Index] := TVector3i.Create;
end;

{ TInteger4Locations }

procedure TInteger4Locations.AddValue(Index: Integer);
begin
  Value[Index] := TVector4i.Create;
end;

{ TFloat1fLocations }

procedure TFloat1fLocations.AddValue(Index: Integer);
begin
  Value[Index] := TSingle.Create;
end;

end.
Что-то типа этого, классы TVector3i, TVector4i и т.д. уж не знаю, как там у вас выглядят. Весь смысл в том, чтобы унаследовать их всех от одного класса TPoint (я понял, что это у вас точки в пространствах разной размерности).

Последний раз редактировалось Kapitoshka438, 03.06.2010 в 04:30.
Ответить с цитированием
  #3  
Старый 03.06.2010, 04:42
Kapitoshka438 Kapitoshka438 вне форума
Начинающий
 
Регистрация: 09.11.2009
Сообщения: 145
Репутация: 238
По умолчанию

Можно еще вот так.
Код:
unit Unit2;

interface

type
  TPoint = class
  end;

  TVector3i = class(TPoint)
    X1, X2, X3: Integer;
  end;

  TVector4i = class(TPoint)
    X1, X2, X3, X4: Integer;
  end;

  TSingle = class(TPoint)
    X1: Single;
  end;

  TPointClass = class of TPoint;

  TBaseLocations = class
    FClassIndex: Integer;
    Location : array of Integer;
    Name: array of ^string;
    Value: array of TPoint;
    procedure SetLengthFor(NewLength: Integer);
    destructor Destroy; override;
  end;

  TInteger3Locations = class(TBaseLocations)
    constructor Create;
  end;

  TInteger4Locations = class(TBaseLocations)
    constructor Create;
  end;

  TFloat1fLocations = class(TBaseLocations)
    constructor Create;
  end;

var
  PointsClasses: array [1..3] of TPointClass = (TVector4i, TVector3i, TSingle);

implementation

{ TBaseLocations }

destructor TBaseLocations.Destroy;
var
  I: Integer;
begin
  for I := Low(Value) to High(Value) do
    Value[i].Free;
  inherited;
end;

procedure TBaseLocations.SetLengthFor(NewLength: Integer);
var
  I: Integer;
begin
  SetLength(Location, NewLength);
  SetLength(Name, NewLength);
  SetLength(Value, NewLength);
  for I := 0 to NewLength - 1 do begin
    Value[i] := PointsClasses[i].Create;
    New(Name[i]);
  end;
end;

{ TInteger3Locations }

constructor TInteger3Locations.Create;
begin
  FClassIndex := 2;
end;

{ TInteger4Locations }

constructor TInteger4Locations.Create;
begin
  FClassIndex := 1;
end;

{ TFloat1fLocations }

constructor TFloat1fLocations.Create;
begin
  FClassIndex := 3;
end;

end.
Ответить с цитированием
Ответ


Delphi Sources

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB-коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход


Часовой пояс GMT +3, время: 10:42.


 

Сайт

Форум

FAQ

Соглашения

Прочее

 

Copyright © Форум "Delphi Sources" by BrokenByte Software, 2004-2025