[fpc-pascal] TObject
Joao Morais
post at joaomorais.com.br
Mon Sep 8 14:46:33 CEST 2008
Carsten Bager wrote:
> A have a unit (uSafeVar) with an object. The object has a property "data" of the type
> "SafeVar_typ"
>
> If I do this it works (wSafeVar is called)
>
> var
> p:SafeVar_typ;
> begin
> p.d:=111;
> SafeVar.data:=p;
Here the Data setter is called, ie, wSafeVar, because you are assigning
a new value to it.
> end
>
>
> If I do this it dos not work but it compiles (wSafeVar is not called)
>
> begin
> SafeVar.data.d:=111;
Here the Data getter is called, ie, hSafeVar, because you are reading a
value from it.
Use a function as a getter instead of a class member. Btw getters and
setters have not the same syntax, you need to create two different methods.
--
Joao Morais
> end;
>
> If I do a read like this ( after the line SafeVar.data.d:=111;)
> Writeln(SafeVar.data.d);
> the output is 111
>
> The compiler is
> Free Pascal Compiler version 2.2.2 [2008/08/26] for arm
>
> Of course I could create a property fore every variable I want to save, but in the real
> program it is a big record, so I thought this was a smart way to get around this.
> Is it in fact an error that it compiles?
>
>
> Carsten
>
>
> --------------------------------------------------------------------------
> Unit uSafeVar;
> {$mode objfpc}
>
>
> Interface
>
> Uses
> sysutils,
> Classes;
>
> Type
> SafeVar_typ = packed record
> d:byte;
> end;
>
> TSafeVar=class(TObject)
> Private
> hSafeVar:SafeVar_typ;
> f:file of SafeVar_typ;
> Procedure wSafeVar(data:SafeVar_typ);
> Public
> constructor create;
> destructor destroy; override;
> property data:SafeVar_typ read hSafeVar write wSafeVar;
> Published
> end;
>
>
>
> var
> SafeVar:TSafeVar;
>
> implementation
>
> constructor TSafeVar.create;
> Begin
> inherited Create;
> fillchar(hSafeVar,sizeof(SafeVar_typ),chr(0));
> assign(f,SafeVar_dat);
> if fileexists(SafeVar_dat) then
> begin
> reset(f);
> read(f,hSafeVar);
> end else
> begin
> rewrite(f);
> Write(f,hSafeVar);
> end;
> End;
>
> destructor TSafeVar.destroy;
> Begin
> inherited destroy;
> close(f);
> End;
>
> Procedure TSafeVar.wSafeVar(data:SafeVar_typ);
> Begin
> hSafeVar:=data;
> seek(f,0);
> Write(f,data);
> End;
>
> initialization
> SafeVar:=tSafeVar.create;
> finalization
> SafeVar.free;
> End.
> ------------------------------------------
>
More information about the fpc-pascal
mailing list