开发者

Custom class to string

开发者 https://www.devze.com 2023-01-17 06:52 出处:网络
Hi I\'ve created a custom class called Tperson. I\'d like to convert this to a string so I can save it to an array( of type Tperson) and display in a string grid.

Hi I've created a custom class called Tperson. I'd like to convert this to a string so I can save it to an array( of type Tperson) and display in a string grid.

unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TPerson = class(Tobject)
  public
    Fname   : string;
    Fage    : integer;
    Fweight : integer;
    FHeight : integer;
    FBMI    : real;

    function GetBMI(Fweight,Fheight:integer) : real;
    procedure create(Fname:String;fage,fweight,fheight:integer);overload;
    procedure Persontostr(Fname:string;Fage,Fheigth,Fweight:integer;FBMI:real);overload;
  end;

implementation

{ TPerson }



procedure TPerson.create(Fname: String; fage, fweight, fheig开发者_JAVA技巧ht: integer);
begin
    Fname := '';
    Fage := 0;
    Fweight := 0;
    FHeight := 0;
    FBMI := 0;
end;

function TPerson.GetBMI(Fweight, Fheight: integer): real;
begin
  result := (Fweight/Fheight) * (Fweight/Fheight);
end;

procedure TPerson.Persontostr(Fname:string;Fage,Fheigth,Fweight:integer;FBMI:real);
begin

end;

end.


Which fields do you want to convert to string?

If all then you can do something like:

function TPerson.ToString: string;
begin
  Result := Format('%s, %d years, %d kg, %d cm, BMI: %.f', [FName, FAge, FWeight, FHeight, FBMI]);
end;

What do you want with the procedure Persontostr. It looks like a setter procedure to me. Although the name implies an other function.

Further, you should make your fields private. So you can add properties. BMI should be readonly:

type
  TPerson = class(Tobject)
  private
    // Object fields, hidden from outside.
    FName   : string;
    FAge    : integer;
    FWeight : integer;
    FHeight : integer;

    // Getter function for calculated fields.
    function GetBMI: Real; // Calculates BMI.
  public
    // Constructor, used to initialise the class
    constructor Create(const AName: string; const AAge,AWeight, AHeight: integer);

    // Properties used to control access to the fields.
    property Name: string read FName;
    property Age: Integer read FAge;
    property Weight: Integer read FWeight;
    property Height: Integer read FHeight;
    property BMI: Real read GetBMI;
  end;
0

精彩评论

暂无评论...
验证码 换一张
取 消