一般情況下, 類都會定義在 interface 區; 在 implementation 區定義的類 只能本單元使用.
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;
{類定義, 因為已經在 Type 區了, 可以省略 Type 關鍵字}
TMyClass = class
procedure MyProc(var x: Integer);
function MyFun (var x: Integer): Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{TMyClass 中方法的實現}
function TMyClass.MyFun(var x: Integer): Integer;
begin
x := x * 2;
Result := x;
end;
procedure TMyClass.MyProc(var x: Integer);
begin
x := x * 2;
end;
//調用測試
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
myClass: TMyClass; {對象聲明}
begin
myClass := TMyClass.Create; {對象建立}
i := 6;
myClass.MyProc(i); {調用方法}
ShowMessage(IntToStr(i)); {12}
i := 6;
i := myClass.MyFun(i); {調用方法}
ShowMessage(IntToStr(i)); {12}
myClass.Free; {對象釋放}
end;
end.