PDA

View Full Version : Trubble with arrays + classes



Mrwb
03-12-2003, 04:02 PM
Im creating a tile based game, and have created a map class.
The map class contains an array which holds the tile information and some other stuff.

Map class:


type
TDPMap = class (TObject)
StartX: integer;
StartY: integer;
Map: array[0..MapHeight-1,0..MapWidth-1] of integer;
MapCollision: array[0..MapHeight-1,0..MapWidth-1] of integer;
procedure LoadMap(Map: string; MapClass: array of TDPMap);
procedure SaveMap(MapName: string; MapClass: array of TDPMap);
end;


When executing the below code, I get an access violation :(
(Temp is a local integer)


Temp:=Map.map[Y,X];


So my question is: whats wrong? can't you access arrays within a class like you would with a "ordinary" array?

Harry Hunt
03-12-2003, 04:24 PM
First of, just a general tip: Even though you can omit the "private, public, published" you shouldn't for greater readabiltiy and to make sure that things don't get mixed up.

Secondly, if you get an Access Violation that most likely means that you haven't created your TDPMap object. Even though you don't need to have your own constructor, you'll have to call the inherited one.

So do this
Map := TDPMap.Create;
and to free it call
Map.Free;


Although this has nothing to do with your problem, I would recommend that you turn all variables in your class into properties. To create an array property do this

private
FMyArray: array[1..MapWidth - 1, 1..MapHeight - 1] of Integer;
public
property MyArray[X, Y: Integer]: Integer read GetValue write SetValue;

in GetValue do

Result := FMyArray[X, Y]

and in SetValue do

FMyArray[X, Y] := Value;

You don't have to do this, but it's always good to follow the standards.

Mrwb
03-12-2003, 06:28 PM
Thanks for the quick reply! :D

It works just perfect now, I have also "converted" the variables to properties like you suggested me to. ;)

Thanks again! :)