Understand the Delphi class (i)

Source: Internet
Author: User

Unit Unit1;

interface
uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, StdCtrls;
type
 TForm1 = class(TForm)
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
 end;
var
 Form1: TForm1;
implementation
{$R *.dfm}
Type
 TMyRecord = record {定义结构}
  d: TDate;
 end;
 TMyClass = class  {定义类; 虽然这个类没有什么实际意义, 但就是一个类了}
  d: TDate;
 end;
procedure TForm1.Button1Click(Sender: TObject);
var
 MyRec: TMyRecord; {声明一个结构变量}
 MyCls: TMyClass; {声明一个类变量, 也就是对象}
begin

{Use structure}

 MyRec.d := Now;
 ShowMessage(DateToStr(MyRec.d));   {2008-1-11}
 ShowMessage(IntToStr(SizeOf(MyRec))); {8; MyRec 结构的大小是 8}

{Use class}

 MyCls := TMyClass.Create;       {需要先手动建立, 因为类需要 实例化为对象才可以使用}
 MyCls.d := Now;            {2008-1-11}
 ShowMessage(DateToStr(MyCls.d));
 ShowMessage(IntToStr(SizeOf(MyCls))); {4; 怎么会是4? 因为 MyCls 对象只是一 个指针!}

Mycls.free; {Release} when finished

Conclusion

A structure (or a record) and a class are all custom types;

The structure is used directly, and the memory is automatically managed;

Class is just a model that needs to be created (create) objects based on the model (i.e. class) to be used, and the memory needs to be freed manually;

(The pattern of memory usage should be: Automatically set up automatic release, manually set up manual release)

Structures and objects (instances of classes) are stored in different ways in memory, and objects are just a pointer;

The class has more powerful features than the structure!

}

End

End.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.