自定义类到字符串

时间:2010-09-20 08:28:34

标签: delphi

您好我已经创建了一个名为Tperson的自定义类。我想将其转换为字符串,以便将其保存到数组(Tperson类型)并显示在字符串网格中。

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, fheight: 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.

1 个答案:

答案 0 :(得分:3)

您想将哪些字段转换为字符串?

如果只有你可以做的事情:

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

Persontostr程序你想要什么?对我来说,它看起来像一个制定者程序。虽然这个名字意味着另一个功能。

此外,您应该将您的字段设为私有。所以你可以添加属性。 BMI应该是只读的:

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;
相关问题