Can anyone tell us why this Lazarus/Pascal code is a mistake?

Asked

Viewed 88 times

0

It is a simple class with get and set methods, but it generates an error when invoking any of the functions or procedures (at first I thought this only on line 43).

unit uPais;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Dialogs;

type
  Pais = class
    private
      codigo:integer;
      descricao:string;
    public
      constructor Create; // construtor
      destructor  Destroy; // destrutor
      // Setters
      procedure setCodigo(pCodigo:integer);
      procedure setDescricao(pDescricao:string);
      // Getters
      function getCodigo():integer;
      function getDescricao():string;

  end;// fim da classe

implementation
constructor Pais.Create();
begin
  codigo := 0;
  descricao := '';
end;

destructor Pais.Destroy();
begin
  //Freemem(@codigo);
  //Freemem(@descricao);
end;

// Setters
procedure Pais.setCodigo(pCodigo:integer);
begin
  codigo := pCodigo;
end;

procedure Pais.setDescricao(pDescricao:string);
begin
  descricao := pDescricao;
end;

// Getters
function Pais.getCodigo():integer;
begin
  Result := codigo;
end;

function Pais.getDescricao():string;
begin
  Result := descricao;
end;

end.
  • I think you could put in the statement which error was displayed.

  • No error was displayed, Lazarus only generates an error points an error in the lines where I try to do the assignments ex: (code := pcodigo)

1 answer

0

In Object Pascal, the correct is to use property, thus:

unit uPais;

{$mode objfpc}{$H+}

interface

uses Classes, SysUtils, Dialogs;

type
    Pais = class
    private
      fCodigo: Integer; // por convenção insira um "f" antes do nome do campo
      fDescricao: string;

      procedure SetCodigo(Value: Integer);
      procedure SetDescricao(Value: string);
    public
        constructor Create; // construtor
        destructor  Destroy; // destrutor

        property Codigo Integer read fCodigo write SetCodigo;
        property Descricao string read fDescricao write SetDescricao;

    end;// fim da classe

implementation

constructor Pais.Create;
begin
    fCodigo    := 0;
    fDescricao := '';
end;

destructor Pais.Destroy;
begin
    //Freemem(@codigo);
    //Freemem(@descricao);
end;

// Setters
procedure Pais.SetCodigo(Value: Integer);
begin
    fCodigo := Value;
end;

procedure Pais.SetDescricao(Value: string);
begin
    fDescricao := Value;
end;

end.

If you wish, create the getters likewise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.